[英]Robolectric test and LiveData
為了完全了解Kotlin,LiveData和Robolectric,我得到了一個簡單的啟動畫面活動。
它在運行應用程序時正常工作,但無法在測試中工作。 就像實時數據的回調永遠不會被觸發一樣,或者就像沒有為它注冊的oberver一樣。
這是測試:
@Test
fun should_redirect_to_login_when_time_is_up_after_onStart() {
val timeUp = MutableLiveData<Boolean>()
kodein.addConfig {
bind<SplashViewModel>(overrides = true) with factory {
_: BaseActivity -> mock<SplashViewModel> { on { isTimeUp() } doReturn timeUp }
}
}
val activity = Robolectric.buildActivity(SplashActivity::class.java).create().start().resume().get()
timeUp.value = true
val startedIntent = shadowOf(activity).nextStartedActivity
assertThat(startedIntent).isNotNull
assertThat(startedIntent).hasComponent(application.packageName, LoginActivity::class.java)
}
活動:
class SplashActivity : JapetActivity() {
lateinit var viewModel: SplashViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
viewModel = kodein.with(this).instance()
viewModel.isTimeUp().observe(this, Observer<Boolean?> { b -> transitionIfTimeUp(b ?: false) })
transitionIfTimeUp(viewModel.isTimeUp().value ?: false)
}
private fun transitionIfTimeUp(isTimeUp: Boolean) {
if (isTimeUp) {
startActivity(Intent(this, LoginActivity::class.java))
finish()
}
}
}
視圖模型(無論如何都會被模擬,因此不使用實現):
/**
* ViewModel for data of the splash screen
*/
interface SplashViewModel {
/** Have we shown the splash screen long enough? */
fun isTimeUp(): LiveData<Boolean>
}
/**
* Default implementation of the view model
*/
class SplashViewModelImpl : ViewModel(), SplashViewModel {
companion object {
private const val SPLASH_DURATION_MS = 2000L
}
private val isTimeUp = MutableLiveData<Boolean>()
init {
isTimeUp.value = false
Observable.timer(SplashViewModelImpl.SPLASH_DURATION_MS, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe { isTimeUp.value = true }
}
override fun isTimeUp(): LiveData<Boolean> = isTimeUp
}
看起來Robolectric沒有觸發Android生命周期方法,因此LiveData不會更新觀察者。 我能夠通過在Robolectric創建活動后手動觸發“ON_START”生命周期事件來解決這個問題:
activity.lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.