收到 kotlin 错误“等待 60000 毫秒后,测试协程未完成”

Jon*_*nas 21 android kotlin kotlin-coroutines kotlin-flow

我是测试新手,试图获取第二个流量值并断言它,当我逐个运行此测试时运行良好,但是当我运行整个测试时,第一个测试运行良好,其余测试给我超时错误。

错误 :

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)
Run Code Online (Sandbox Code Playgroud)
@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()
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 11

我遇到过同样的问题。替换UnconfinedTestDispatcher()StandardTestDispatcher()即可解决问题。

  • 虽然我同意“StandardTestDispatcher”通常比“UnconfinedTestDispatcher”更好,但这不是一个“一刀切”的解决方案,如果您不解释或链接到两者之间的差异,我认为它没有太大帮助。 (3认同)

sam*_*m_k -3

当您使用 runTest 时,默认情况下使用StandardTestDispatcher意味着它不会立即运行。您必须从用于 ViewModel 的同一个调度程序启动测试

代替

runTest {
Run Code Online (Sandbox Code Playgroud)

testDispather.runTest {
Run Code Online (Sandbox Code Playgroud)

它应该有效,尝试一下。如果不检查您的视图模型代码,我就无法分享太多内容。