I am writing unit tests for Android which use coroutines. I am using StandardTestDispatcher
and runTest
for that. At some point in my code there is a call to withTimeout(Long)
function. All tests that call this function fail with TimeoutCancellationException
. However everything works when I use runBlocking
instead of runTest
.
How can I avoid the exception and make tests pass?
Example declaration for unit tests is as follows:
class ExampleTest {
@get:Rule
val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()
val mainDispatcher = StandardTestDispatcher()
@Before
open fun setUp() {
Dispatchers.setMain(mainDispatcher)
}
@Test
fun `example test`() = runTest {
// code that calls withTimeout
}
@After
open fun tearDown() {
Dispatchers.resetMain()
}
}