android - 如何在 Robolectric 4.3.1 上阴影 Kotlin 伴侣对象?
问题描述
我想遮蔽一个 Kotlin 伴生对象。我想要阴影的伴随对象是:
class MyLogClass {
companion object {
@JvmStatic
fun logV(tag: String, messageProvider: () -> String) {
if (SPUtils.getLogLevel() >= mLogLevel) {
Log.v(tag, messageProvider.invoke())
}
}
}
}
我试过的:
// Shadow class...
@Implements(MyLogClass.Companion::class)
class ShadowMyLogClass {
@Implementation
fun v(tag: String, messageProvider: () -> String) {
redirectConsole(tag, messageProvider)
}
private fun redirectConsole(tag: String, messageProvider: () -> String) {
println("[$tag]${messageProvider.invoke()}")
}
}
// And in Testing class...
class TestMyLogClass {
@Test
fun test() {
MyLogClass.logV("some tag") {
"some message"
}
}
}
但是我尝试过的发生错误:
Caused by: java.lang.IllegalAccessError: tried to access class kotlin.jvm.internal.DefaultConstructorMarker from class com.example.zspirytus.log.impl.MyLogClass$Companion
似乎丢失了一个构造方法,类型是DefaultConstructorMarker
什么,我怎样才能制作一个DefaultConstructorMarker
或其他方式来创建一个影子MyLogClass
?感谢您的阅读和回答!
解决方案
这是我在伴生对象中隐藏方法的操作
@Implements(Object::class)
class ShadowObject {
companion object {
@Implementation
@JvmStatic
fun verify(): Boolean {
return true
}
}
}
利用:
@RunWith(AndroidJUnit4::class)
@Config(shadows = [
ShadowObject::class
])
class UserTest {
// Rest of testing class
}
在你的情况下,我想说你只需要用 包装你的 @Implementation 方法companion object
,然后@Implements(MyLogClass.Companion::class)
改为@Implements(MyLogClass::class)
推荐阅读
- html - 如何将表格行溢出到第二列?
- css - 仅在块中的 CSS 背景动画
- php - 使用 PHP 和 Twig 创建等待页面
- r - ggraph 根据关键字更改 geom_node_text 颜色
- docker - 如何使用主机网络运行 docker-compose?
- mysql - AWS DMS:Mariadb 10 到 Aurora MySQL 5.7 - 迁移和复制
- javascript - 如何访问对象数组中的两个单独的图像并将其分配给同一数组中的第三个对象?
- django - ModuleNotFoundError Django 视图
- ios - 将 Firebase 事件推送到表视图
- python - 有时通过 adb 截屏图片打不开