这是我在 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)
}
当运行这个测试结果是错误的
论据不同!通缉:observer.onChanged(true); -> 在 com.example.kotlinmvvm.feature.splash.viewModel.SplashViewModelTest。调用 getIsLoggedLiveData 时应检查配置用户登录状态(SplashViewModelTest.kt:85)
实际调用有不同的参数:observer.onChanged(false); -> 在 androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
比较失败:
预期:observer.onChanged(true);
实际:observer.onChanged(false);
谁知道发生了什么事?