使用TestCoroutineDispatcher(弃用)替代方案对Kotlin协同程序进行Android测试

djp7away  于 2023-02-14  发布在  Android
关注(0)|答案(2)|浏览(227)

我正在调查我的Android应用程序中的协程测试,并遵循此代码实验室Advanced Android in Kotlin 05.3: Testing Coroutines and Jetpack integrations
此代码实验室包含以下代码片段

@ExperimentalCoroutinesApi
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()

@ExperimentalCoroutinesApi
@Before
fun setupDispatcher() {
    Dispatchers.setMain(testDispatcher)
}

@ExperimentalCoroutinesApi
@After
fun tearDownDispatcher() {
    Dispatchers.resetMain()
    testDispatcher.cleanupTestCoroutines()
}

但是,TestCoroutineDispatcher标记为已弃用,并带有以下注解:-

/**
 * [CoroutineDispatcher] that performs both immediate and lazy execution of coroutines in tests
 * and uses a [TestCoroutineScheduler] to control its virtual clock.
 *
 * By default, [TestCoroutineDispatcher] is immediate. That means any tasks scheduled to be run without delay are
 * immediately executed. If they were scheduled with a delay, the virtual clock-time must be advanced via one of the
 * methods on the dispatcher's [scheduler].
 *
 * When switched to lazy execution using [pauseDispatcher] any coroutines started via [launch] or [async] will
 * not execute until a call to [DelayController.runCurrent] or the virtual clock-time has been advanced via one of the
 * methods on [DelayController].
 *
 * @see DelayController
 */
@Deprecated("The execution order of `TestCoroutineDispatcher` can be confusing, and the mechanism of " +
    "pausing is typically misunderstood. Please use `StandardTestDispatcher` or `UnconfinedTestDispatcher` instead.",
    level = DeprecationLevel.WARNING)
// Since 1.6.0, ERROR in 1.7.0 and removed as experimental in 1.8.0
public class TestCoroutineDispatcher(public override val scheduler: TestCoroutineScheduler = TestCoroutineScheduler()):
    TestDispatcher(), Delay, SchedulerAsDelayController
{...}

我不清楚应该如何使用建议的TestCoroutineDispatcher()替代方法。StandardTestDispatcherUnconfinedTestDispatcher是否直接替代TestCoroutineDispatcher()?
我错过了什么?

m1m5dgzv

m1m5dgzv1#

似乎可以使用更优雅的解决方案,如runTest(),因为1.6.0
取自此销售订单answer
有关如何使用该模块的详细信息,请参见documentation

dzhpxtsq

dzhpxtsq2#

Ide建议使用StandardTestDispatcher(),但是,它的行为不像TestCoroutineDispatcher(),因为StandardTestDispatcher()不会立即进入launch{}async{}。因此,最好使用UnconfinedTestDispatcher()。我建议你查看android studio中的快速文档来了解这个想法。

相关问题