我正在遵循Craig Russell的博客文章,该文章介绍了有关测试协程的内容:https://craigrussell.io/2019/11/unit-testing-coroutine-suspend-functions-using-testcoroutinedispatcher/但是我无法通过此测试:
@Test
fun multipleLaunch() = runBlockingTest {
var result = 0
val jobs = mutableListOf<Job>()
for (j in 0 until 10) {
val job = launch(testDispatcherProvider.io()) {
delay(1000)
result++
}
jobs.add(job)
}
jobs.forEach { job ->
job.join()
}
assertEquals(10, result)
}
基本上我要启动一堆并行作业,希望在它们全部完成后得到结果。 到目前为止,我已经遇到了一个经典的例外:
java.lang.IllegalStateException: This job has not completed yet
请指导如何按预期工作。
我的完整代码:
class LaunchTest { @get:Rule var coroutinesTestRule = CoroutineTestRule() val testDispatcherProvider = object : DispatcherProvider { override fun io(): CoroutineDispatcher = coroutinesTestRule.testDispatcher } @Test fun multipleLaunch() = runBlockingTest { var result = 0 val jobs = mutableListOf<Job>() for (j in 0 until 10) { val job = launch(testDispatcherProvider.io()) { delay(1000) result++ } jobs.add(job) } jobs.forEach { job -> job.join() } assertEquals(10, result) } } class CoroutineTestRule constructor(val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()) : TestWatcher() { override fun starting(description: Description?) { super.starting(description) Dispatchers.setMain(testDispatcher) } override fun finished(description: Description?) { super.finished(description) Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } }
runBlocking
而不是runBlockingTest
。 - Animesh Sahu