【发布时间】:2022-07-13 23:28:10
【问题描述】:
我是测试新手,试图获取第二个流值并断言它,当我一个接一个地运行这个测试时运行良好,但是当我运行整个测试时,一旦第一个测试运行良好,其余的测试给我超时错误。
错误:
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()
}
}
【问题讨论】:
-
如何更新
homeUiState的值?确定更新了吗? -
看起来
homeUiState在每个测试会话中始终只更新一次,因此只有第一个测试完成。您是否在HomeViewModel的实例之间共享一些状态/对象,这可能导致homeUiState仅更新一次,即使创建了多个HomeViewModel实例也是如此?
标签: android kotlin kotlin-coroutines kotlin-flow