Kotlin,Mockito和Android测试仪器。 Lateinit Property尚未初始化

时间:2017-11-06 22:51:20

标签: android kotlin mockito

我正在尝试在测试工具中模拟UseCase依赖项。

我正在创建一个@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!!
    }


}

1 个答案:

答案 0 :(得分:1)

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

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