我正在写一个单元测试。下面是我的代码。该架构是使用 Dagger2 的 MVVM。我正在调用位于 LoginViewModel 中的登录函数,它通知 getLoginState 函数。我得到的错误是:
错误:
io.mockk.MockKException: no answer found for: Observer(#8).onChanged(Success(data=))
at io.mockk.impl.stub.MockKStub.defaultAnswer(MockKStub.kt:90)
登录视图模型类:
fun logIn(phone: String, phoneCode: String) {
loginState.value = Outcome.success("")
}
fun getLoginState(): LiveData<Outcome<String>> = loginState
LoginViewModelTest 类:
@RelaxedMockK
var SUT: LoginViewModel? = null
@Mock
var loginInteractor: LoginInteractor? = null
@Mock
var textValidator: TextValidator? = null
@Mock
var textProvider: TextProvider? = null
@Mock
var blinkUserPreferences: BlinkUserPreferences? = null
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
@RelaxedMockK
var mockObserver: Observer<Outcome<String>>? = null
@Before
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
SUT = spyk(
LoginViewModel(
mockk<LoginInteractor>(),
mockk<TextValidator>(relaxed = true),
mockk<TextProvider>(),
mockk<BlinkUserPreferences>()))
mockObserver = mockk<Observer<Outcome<String>>>()
SUT!!.getLoginState().observeForever(mockObserver!!)
}
@Test
fun logIn() {
//Arrange
every {SUT!!.getLoginState().value} returns Outcome.success("")
//Act
SUT!!.logIn("89989676","89998")
//Assert
verify() { mockObserver!!.onChanged(Outcome.success("abc")) }
}
问题: 在验证中,为什么没有调用 onChanged 方法,或者没有找到 Observer().onChanged 的答案是什么意思,我如何通知我的 onChanged 方法以便我可以验证它?