I'm trying to write test for my ViewModel method. Here is part of code from my ViewModel:
fun makeBackgroundCallAndClose() {
backgroundScope.launch(genericErrorHandler) {
interactor.doBackground(null)
}
navigate(NavigatorCommand.CloseScreen)
}
The essence of the method is to make API call and close the screen without waiting for a response. On a real device, this works as I would expect, however my tests fail.
Here is my test:
@Test
fun `test my makeBackgroundCallAndClose`() = runTest(testDispatcher) {
coEvery { interactor.doBackground(any()) } just runs
val viewModel = MyViewModel(
interactor,
TestScope()
)
viewModel.makeBackgroundCallAndClose()
runCurrent()
coVerify {
interactor.doBackground(null)
}
}
Me test fails with error: Verification failed: call 1 of 1: MyInteractor(interactor#2).doBackground(null(), any())) was not called.
As far as I understand, my test completes until the request doBackground call is completed, I tried to set a timeout, but it did not help, please help me, what am I doing wrong.
It seems the backgroundScope
wasn't mocked.
Can you show the MyViewModel constructor?
If the second argument is backgroundScope
, you should pass your TestScope to viewModel.
@Test
fun `test my makeBackgroundCallAndClose`() = runTest {
coEvery { interactor.doBackground(any()) } just runs
// or use coJustRun { interactor.doBackground(any()) }
val viewModel = MyViewModel(
interactor,
this,
)
viewModel.makeBackgroundCallAndClose()
runCurrent()
coVerify {
interactor.doBackground(null)
}
}