我有一个类,它采用协程调度程序作为我正在尝试测试的参数。在我的测试中,我在每次测试运行之前使用 @Before
设置我的类
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() = runTest {
.....
val dispatcher = StandardTestDispatcher(testScheduler)
scheduleService = ScheduleService(dispatcher)
}
我正在尝试运行一个测试,其中有一个 SharedFlow
,我想检查它的值,因此我还在该测试中使用 runTest
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testFullScheduleCreation() = runTest{
......
val data = scheduleService.scheduleChangedListener.first()
}
当我尝试运行测试时出现错误
Detected use of different schedulers. If you need to use several test coroutine dispatchers, create one TestCoroutineScheduler and pass it to each of them.
该错误是因为我使用了@Before
,但我不确定如何在不将该设置方法中的所有代码复制到每个测试的情况下修复该错误
最佳答案
有几种方法可以在测试之间共享调度程序。最简单的方法是在设置中调用 Dispatchers.setMain(...)
。如果主调度程序设置为 TestDispatcher,则 runTest 函数将使用它进行所有后续测试。
@Before
fun setup() {
val dispatcher = StandardTestDispatcher()
scheduleService = ScheduleService(dispatcher)
Dispatchers.setMain(dispatcher)
}
如果您使用此方法,您还应该在测试拆卸函数中调用 Dispatchers.resetMain()
。
如果您喜欢手动执行此操作,也可以将调度程序传递给 runTest
。
lateinit var dispatcher: TestDispatcher
@Before
fun setup() {
dispatcher = StandardTestDispatcher()
scheduleService = ScheduleService(dispatcher)
}
@Test
fun myTest() = runTest(dispatcher) {
...
}
作为替代方案,您还可以调用 scope.runTest
来使用包含调度程序的共享作用域。
lateinit var scope: TestScope
@Before
fun setup() {
val dispatcher = StandardTestDispatcher()
scope = TestScope(dispatcher)
scheduleService = ScheduleService(dispatcher)
}
@Test
fun myTest() = scope.runTest {
...
}
关于unit-testing - 使用协程进行测试时检测到使用不同的调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74278821/