https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Marek Kubiczek

07/14/2022, 9:07 AM
I am testing viewModel using the new coroutines testing framework and Mockk library. It seems that the exceptions from child coroutines are swallowed though. It looks more or less like this example:
Copy code
@Before
fun setUp() {
  Dispatchers.setMain(UnconfinedTestDispatcher())
}

@Test
fun `Some exemplary test`() = runTest {
    val dependency1 = mockk<Dependency1>()
    val viewModel = TestedViewModel(dependency1)
    viewModel.testedMethod()
    coVerify(exactly = 1) { dependency1.methodToBeCaled() }
}
The ViewModel itself is calling that method in viewModelScope
Copy code
fun testedMethod() {
  viewModelScope.launch {
    methodToBeCalled()
  }
}
However I forgot to mock the called method. I am seeing in log
Copy code
Exception in thread "Test worker @coroutine#7" io.mockk.MockKException: no answer found for: Dependency1(#1).methodToBeCalled(continuation {})
But the test passes. Is it known issue?
e

ephemient

07/14/2022, 9:50 AM
https://github.com/Kotlin/kotlinx.coroutines/issues/3298 coroutines in viewModelScope under setMain don't run immediately as expected :(
m

Marek Kubiczek

07/14/2022, 9:55 AM
And according to runTest doc
Unhandled exceptions will be thrown at the end of the test. If the uncaught exceptions happen after the test finishes, the error is propagated in a platform-specific manner. If the test coroutine completes with an exception, the unhandled exceptions are suppressed by it.
that’s the case here right?
e

ephemient

07/14/2022, 10:04 AM
I believe so. you could add more logging to check that is the order of operations
116 Views