Getting kotlin error "After waiting for 60000 ms, the test coroutine is not completing"

Viewed 796

I'm new at testing, trying to take second flow value and assert it, When i run this test one by one runs fine but when i run whole test once first test runs fine and rest of test give me timeout error.

Error :

After waiting for 60000 ms, the test coroutine is not completing
kotlinx.coroutines.test.UncompletedCoroutinesError: After waiting for 60000 ms, the test coroutine is not completing
    at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTestCoroutine$3$3.invokeSuspend(TestBuilders.kt:304)
    (Coroutine boundary)
@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModelTest {

    private lateinit var viewModel: HomeViewModel
    private val testDispatcher = UnconfinedTestDispatcher()

    @Before
    fun setup() {
        viewModel = HomeViewModel(FakeOrderRepository())
        Dispatchers.setMain(testDispatcher)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
        testDispatcher.cancel()
    }

    @Test
    fun flowViewModelTesting1() = runTest {
        val result = viewModel.homeUiState.drop(1).first()
        assertThat(true).isTrue()
    }


    @Test
    fun flowViewModelTesting2() = runTest {
        val result = viewModel.homeUiState.drop(1).first()
        assertThat(true).isTrue()
    }
}
3 Answers

I had the same issue. Replacing UnconfinedTestDispatcher() with StandardTestDispatcher() will solve the problem.

Most of the time reason for this error is that you have not finish your observer variable call.

At the end of your test case call finish() method on your observer variable.

observerVariable.finish()

When you use runTest, so you're using StandardTestDispatcher by default that means it won't immediately run. You have to launch your test from the same dispatcher that you have been using for a ViewModel

Replace

runTest {

with

testDispather.runTest {

it should work, give it a try. I can't share much without checking your viewmodel code.

Related