【问题标题】:The TestScope advanced example of usage in tests with coroutines协程测试中使用的 TestScope 高级示例
【发布时间】:2022-01-02 00:08:54
【问题描述】:

有人可以提供一个在使用协程进行测试时使用新的TestScopeTestScope.launch 的高级示例吗?

似乎在新的kotlinx.coroutines.test 版本中,他们在库中添加了一些名为TestScope 的内容。此外,他们已经弃用了旧的TestCoroutineDispatcher,并被告知使用TestScope.runTests,但是,他们没有添加太多关于如何使用它的文档。我能找到的都是this

谁能提供一些在不同场景中的额外使用示例?

【问题讨论】:

  • 不确定我是否理解您的问题。 TestScope 只是 TestCoroutineScope 的替代品。它由顶层runTest 提供为this,就像runBlocking 也为您提供范围一样。因此,使用runtest { ... } 并在内部嵌套launch 可以有效地在测试范围内运行协程。您想要使用嵌套TestScope.runTest 的示例吗?

标签: android unit-testing kotlin kotlin-coroutines


【解决方案1】:

我也可以用评论中提到的@Joffrey 来解决这个问题。 您只需要使用runTest { } 即可在测试代码处使用协程范围。通过使用runTest { },您可以在带有this 的块内使用TestScope

在我的例子中,viewModel 中有一个类似这样的流函数。它在viewModelScope 内运行。

    fun getFriendDataWithFlow() {
        viewModelScope.launch {
            repository.loadFriendsWithFlow()
            ...
        }
     }

我应该在我的测试代码中测试这个,我是这样使用它的。

   @ExperimentalCoroutinesApi
   @Before
   fun setup() {
       Dispatchers.setMain(StandardTestDispatcher())
   }

   @ExperimentalCoroutinesApi
   @Test
   fun temp() {
        runTest {
            viewModel.getFriendDataWithFlow()
        }
   }

我所做的只是添加runTest { } 块,并在块内添加协程代码。它对我有用。 我的测试协程依赖是"org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0-RC"

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    相关资源
    最近更新 更多