首页 > 解决方案 > 如何在 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?感谢您的阅读和回答!

标签: androidkotlinrobolectric

解决方案


这是我在伴生对象中隐藏方法的操作

@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)


推荐阅读