这是我关于stackoverflow的第一篇文章,我是Kotlin的初学者,生命周期,需要帮助。我迷失了2天,需要帮助。
我有SplashViewModel类
class SplashViewModel @Inject constructor(
private val configuration: IConfiguration,
private val compositeDisposable: CompositeDisposable) : BaseViewModel(compositeDisposable), SplashContract.ViewModel{
override val isLoggedLiveData: MutableLiveData<Boolean> = MutableLiveData()
init {
setLoginStatus()
}
override fun setLoginStatus(){
isLoggedLiveData.postValue(configuration.isUserLoggedIn())
}}
SplashViewModelTest类
class SplashViewModelTest : BaseTest(){
@get:Rule
val testRule = InstantTaskExecutorRule()
@Mock
private lateinit var configuration: IConfiguration
@Mock
private lateinit var compositeDisposable: CompositeDisposable
@Mock
private lateinit var observer: Observer<Boolean>
private lateinit var viewModel: SplashContract.ViewModel
override fun setup() {
super.setup()
trampolineRxPlugin()
viewModel = SplashViewModel(
configuration,
compositeDisposable
)
}
override fun tearDown() {
super.tearDown()
verifyNoMoreInteractions(
configuration,
compositeDisposable
)
}
@Test
fun `should change livedata status to true when viewmodel is initialize`() {
val isLogged = true
`when`(configuration.isUserLoggedIn()).thenReturn(isLogged)
viewModel.isLoggedLiveData.observeForever(observer)
verify(configuration, Mockito.times(1)).isUserLoggedIn()
verify(observer).onChanged(isLogged)
}
运行时此测试结果错误
参数不同!通缉: rator.onChanged(true); -> com.example.kotlinmvvm.feature.splash.viewModel.SplashViewModelTest.com上的-应该在调用getIsLoggedLiveData时检查配置用户登录状态(SplashViewModelTest.kt:85)
实际调用具有不同的参数: rator.onChanged(false); ->在androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
比较失败:
预期:observer.onChanged(true);
Actual:observer.onChanged(false);
谁知道发生了什么事?
答案 0 :(得分:0)
我怀疑正在发生的事情是您正在实例化视图模型(在setup
中),然后再调用以下模型(使用isLogged
= true
)...这导致代码在init
中被调用...,此时它将返回false。
`when`(configuration.isUserLoggedIn()).thenReturn(isLogged)
您是否还打算在测试中显式调用setLoginStatus
(在上一行之后)?