Kotlin、Mockito 和 Android Test Instrumentation.Lateinit 属性尚未初



我正在尝试模拟测试仪器中的用例依赖项。

我正在创建一个@Rule来处理这个:

LocationsUseCaseRule.kt

class LocationsUseCaseRule : ExternalResource() {
    @Mock
    lateinit var locationsUseCase : LocationsUseCase
    @Throws(Throwable::class)
    override fun before() {
        super.before()
        LocationsUseCase.setInstance(locationsUseCase)
    }
}

但是当我点击before()时,用例没有加载。

我在单元测试中有相同的实现,它可以工作。

这些是我的依赖项:

// Mockito
def mockitoVersion = "2.6.3"
testCompile 'org.mockito:mockito-core:' + mockitoVersion
androidTestCompile 'org.mockito:mockito-core:' + mockitoVersion
androidTestCompile "org.mockito:mockito-android:" + mockitoVersion
testCompile "com.nhaarman:mockito-kotlin-kt1.1:1.5.0"

这是我在LocationsUseCase中设置实例的方式:

object Singleton {
    var instance: LocationsUseCase? = null
}
companion object {
    fun setInstance(locationsUseCase: LocationsUseCase?) {
        Singleton.instance = locationsUseCase
    }
    fun getInstance(): LocationsUseCase {
        if (Singleton.instance == null) {
            Singleton.instance = LocationsUseCase(
                    LocationsRepository.instance
            )
        }
        return Singleton.instance!!
    }

}

我认为这种方式更简单,可以实现您想要的:

object Singleton {
    val instance = LocationsUseCase(LocationsRepository.instance)
}

相关内容

  • 没有找到相关文章

最新更新