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()
即可解决问题。
sam*_*m_k -3
当您使用 runTest 时,默认情况下使用StandardTestDispatcher
意味着它不会立即运行。您必须从用于 ViewModel 的同一个调度程序启动测试
代替
runTest {
Run Code Online (Sandbox Code Playgroud)
和
testDispather.runTest {
Run Code Online (Sandbox Code Playgroud)
它应该有效,尝试一下。如果不检查您的视图模型代码,我就无法分享太多内容。