To get a hang of Kotlin, LiveData and Robolectric alltogether, I got a simple splash screen activity.
It works properly when running the application, but it fails to work in the test. It is like the live data's callback is never triggered or like if no oberver is registered for it.
Here is the test:
@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)
}
The activity:
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()
}
}
}
The view model (which gets mocked anyway, so implementation is not used):
/**
* 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
}
Aucun commentaire:
Enregistrer un commentaire