【问题标题】:Coroutines - unit testing viewModelScope.launch methods协程 - 单元测试 viewModelScope.launch 方法
【发布时间】:2019-04-19 16:56:21
【问题描述】:

我正在为我的 viewModel 编写单元测试,但在执行测试时遇到了问题。 runBlocking { ... } 块实际上并没有等待里面的代码完成,这让我很惊讶。

测试失败,因为result 是null。为什么runBlocking { ... } 不以阻塞方式在 ViewModel 中运行 launch 块?

我知道如果我将它转换为返回Deferred 对象的async 方法,那么我可以通过调用await() 来获取该对象,或者我可以返回一个Job 并调用join()。 但是,我想通过将 ViewModel 方法保留为 void 函数来做到这一点,有没有办法做到这一点?

// MyViewModel.kt

class MyViewModel(application: Application) : AndroidViewModel(application) {

    val logic = Logic()
    val myLiveData = MutableLiveData<Result>()

    fun doSomething() {
        viewModelScope.launch(MyDispatchers.Background) {
            System.out.println("Calling work")
            val result = logic.doWork()
            System.out.println("Got result")
            myLiveData.postValue(result)
            System.out.println("Posted result")
        }
    }

    private class Logic {
        suspend fun doWork(): Result? {
          return suspendCoroutine { cont ->
              Network.getResultAsync(object : Callback<Result> {
                      override fun onSuccess(result: Result) {
                          cont.resume(result)
                      }

                     override fun onError(error: Throwable) {
                          cont.resumeWithException(error)
                      }
                  })
          }
    }
}
// MyViewModelTest.kt

@RunWith(RobolectricTestRunner::class)
class MyViewModelTest {

    lateinit var viewModel: MyViewModel

    @get:Rule
    val rule: TestRule = InstantTaskExecutorRule()

    @Before
    fun init() {
        viewModel = MyViewModel(ApplicationProvider.getApplicationContext())
    }

    @Test
    fun testSomething() {
        runBlocking {
            System.out.println("Called doSomething")
            viewModel.doSomething()
        }
        System.out.println("Getting result value")
        val result = viewModel.myLiveData.value
        System.out.println("Result value : $result")
        assertNotNull(result) // Fails here
    }
}

【问题讨论】:

  • 请确保您的问题显示一个最小、完整和可验证的示例 (stackoverflow.com/help/mcve),这样会更容易回答您的问题。
  • runBlocking 只会等待子协程。使用 viewModelScope 创建的协程与 runBlocking 内部的范围无关。
  • 更好的方法是将调度程序上下文传递给视图模型,这样您就可以在测试中传递您的测试 dispather..!

标签: android kotlin android-livedata kotlin-coroutines


【解决方案1】:

您需要做的是将您启动的协程包装到具有给定调度程序的块中。

var ui: CoroutineDispatcher = Dispatchers.Main
var io: CoroutineDispatcher =  Dispatchers.IO
var background: CoroutineDispatcher = Dispatchers.Default

fun ViewModel.uiJob(block: suspend CoroutineScope.() -> Unit): Job {
    return viewModelScope.launch(ui) {
        block()
    }
}

fun ViewModel.ioJob(block: suspend CoroutineScope.() -> Unit): Job {
    return viewModelScope.launch(io) {
        block()
    }
}

fun ViewModel.backgroundJob(block: suspend CoroutineScope.() -> Unit): Job {
    return viewModelScope.launch(background) {
        block()
    }
}

注意顶部的 ui、io 和背景。这里的一切都是顶级+扩展函数。

然后在 viewModel 中你像这样开始你的协程:

uiJob {
    when (val result = fetchRubyContributorsUseCase.execute()) {
    // ... handle result of suspend fun execute() here         
}

在测试中你需要在@Before 块中调用这个方法:

@ExperimentalCoroutinesApi
private fun unconfinifyTestScope() {
    ui = Dispatchers.Unconfined
    io = Dispatchers.Unconfined
    background = Dispatchers.Unconfined
}

(添加到 BaseViewModelTest 等基类中会更好)

【讨论】:

  • 你不能在 viewmodel 范围内使用 ui dispatcher 在 ViewModel 中不应该有任何与 UI 相关的内容阅读更多如何使用 ViewModels
  • viewModeScope 的默认调度器已经是 Main Dispatcher @EdgarKhimich
【解决方案2】:

作为 @Gergely Hegedus mentions above,需要将 CoroutineScope 注入到 ViewModel 中。使用此策略,CoroutineScope 作为参数传递,并带有用于生产的默认 null 值。对于单元测试,将使用 TestCoroutineScope。

SomeUtils.kt

/**
 * Configure CoroutineScope injection for production and testing.
 *
 * @receiver ViewModel provides viewModelScope for production
 * @param coroutineScope null for production, injects TestCoroutineScope for unit tests
 * @return CoroutineScope to launch coroutines on
 */
fun ViewModel.getViewModelScope(coroutineScope: CoroutineScope?) =
    if (coroutineScope == null) this.viewModelScope
    else coroutineScope

SomeViewModel.kt

class FeedViewModel(
    private val coroutineScopeProvider: CoroutineScope? = null,
    private val repository: FeedRepository
) : ViewModel() {

    private val coroutineScope = getViewModelScope(coroutineScopeProvider)

    fun getSomeData() {
        repository.getSomeDataRequest().onEach {
            // Some code here.            
        }.launchIn(coroutineScope)
    }

}

SomeTest.kt

@ExperimentalCoroutinesApi
class FeedTest : BeforeAllCallback, AfterAllCallback {

    private val testDispatcher = TestCoroutineDispatcher()
    private val testScope = TestCoroutineScope(testDispatcher)
    private val repository = mockkClass(FeedRepository::class)
    private var loadNetworkIntent = MutableStateFlow<LoadNetworkIntent?>(null)

    override fun beforeAll(context: ExtensionContext?) {
        // Set Coroutine Dispatcher.
        Dispatchers.setMain(testDispatcher)
    }

    override fun afterAll(context: ExtensionContext?) {
        Dispatchers.resetMain()
        // Reset Coroutine Dispatcher and Scope.
        testDispatcher.cleanupTestCoroutines()
        testScope.cleanupTestCoroutines()
    }

    @Test
    fun topCafesPoc() = testDispatcher.runBlockingTest {
        ...
        val viewModel = FeedViewModel(testScope, repository)
        viewmodel.getSomeData()
        ...
    }
}

【讨论】:

    【解决方案3】:

    正如其他人提到的,runblocking 只是阻止在其范围内启动的协程,它与您的 viewModelScope 是分开的。 您可以做的是注入您的 MyDispatchers.Background 并将 mainDispatcher 设置为使用 dispatchers.unconfined。

    【讨论】:

    【解决方案4】:

    我尝试了最佳答案并且工作了,但我不想检查我的所有启动并在我的测试中添加对 main 或 unconfined 的调度程序引用。所以我最终将此代码添加到我的基础测试类中。我将我的调度程序定义为 TestCoroutineDispatcher()

    class InstantExecutorExtension : BeforeEachCallback, AfterEachCallback {
        private val mainThreadDispatcher = TestCoroutineDispatcher()
    
        override fun beforeEach(context: ExtensionContext?) {
            ArchTaskExecutor.getInstance()
                .setDelegate(object : TaskExecutor() {
                    override fun executeOnDiskIO(runnable: Runnable) = runnable.run()
    
                    override fun postToMainThread(runnable: Runnable) = runnable.run()
    
                    override fun isMainThread(): Boolean = true
                })
    
            Dispatchers.setMain(mainThreadDispatcher)
        }
    
        override fun afterEach(context: ExtensionContext?) {
            ArchTaskExecutor.getInstance().setDelegate(null)
            Dispatchers.resetMain()
        }
    }
    

    在我的基础测试类中

    @ExtendWith(MockitoExtension::class, InstantExecutorExtension::class)
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    abstract class BaseTest {
    
        @BeforeAll
        private fun doOnBeforeAll() {
            MockitoAnnotations.initMocks(this)
        }
    }
    

    【讨论】:

    • Don’t use Dispatchers.Unconfined as a replacement of Dispatchers.Main, it will break all assumptions and timings for code that does use Dispatchers.Main. Since a unit test should run well in isolation and without any side effects, you should call Dispatchers.resetMain() and clean up the executor when the test finishes running. 参考:medium.com/androiddevelopers/… .. 标题:Unit Testing viewModelScope 第 4 段...
    • 感谢您的信息。我正在编辑我的答案,因为我发现 TestCoroutineDispatcher 更合适,并且我也在每次测试后应用休息。我记得读过你发布的同一个博客,但它现在有点旧了..
    【解决方案5】:

    您遇到的问题不是源于 runBlocking,而是源于 LiveData 在没有附加观察者的情况下没有传播值。

    我见过很多处理这个问题的方法,但最简单的就是使用observeForever 和CountDownLatch。

    @Test
    fun testSomething() {
        runBlocking {
            viewModel.doSomething()
        }
        val latch = CountDownLatch(1)
        var result: String? = null
        viewModel.myLiveData.observeForever {
            result = it
            latch.countDown()
        }
        latch.await(2, TimeUnit.SECONDS)
        assertNotNull(result)
    }
    

    这种模式很常见,您可能会在某些测试实用程序类/文件中看到许多项目及其一些变体作为函数/方法,例如

    @Throws(InterruptedException::class)
    fun <T> LiveData<T>.getTestValue(): T? {
        var value: T? = null
        val latch = CountDownLatch(1)
        val observer = Observer<T> {
            value = it
            latch.countDown()
        }
        latch.await(2, TimeUnit.SECONDS)
        observeForever(observer)
        removeObserver(observer)
        return value
    }
    

    你可以这样称呼:

    val result = viewModel.myLiveData.getTestValue()

    其他项目将其作为断言库的一部分。

    Here is a library 有人专门写了 LiveData 测试。

    您可能还想查看Kotlin Coroutine CodeLab

    或以下项目:

    https://github.com/googlesamples/android-sunflower

    https://github.com/googlesamples/android-architecture-components

    【讨论】:

    • 我认为问题不在于实时数据没有传播价值。如果我将视图模型中的执行器更改为同步执行器,则测试通过。所以它肯定与协程有关
    • 另外,InstantTaskExecutorRule 规则确保 livedata 立即发布价值
    • 你试过了吗? InstantTaskExecutorRule 只保证 AAC 同步运行,你还需要一个观察者。
    【解决方案6】:

    您不必更改 ViewModel 的代码,唯一需要更改的是在测试 ViewModel 时正确设置协程范围(和调度程序)。

    将此添加到您的单元测试中:

        @get:Rule
        open val coroutineTestRule = CoroutineTestRule()
    
        @Before
        fun injectTestCoroutineScope() {
            // Inject TestCoroutineScope (coroutineTestRule itself is a TestCoroutineScope)
            // to be used as ViewModel.viewModelScope fro the following reasons:
            // 1. Let test fail if coroutine launched in ViewModel.viewModelScope throws exception;
            // 2. Be able to advance time in tests with DelayController.
            viewModel.injectScope(coroutineTestRule)
        }
    
    

    CoroutineTestRule.kt

        @Suppress("EXPERIMENTAL_API_USAGE")
        class CoroutineTestRule : TestRule, TestCoroutineScope by TestCoroutineScope() {
    
        val dispatcher = coroutineContext[ContinuationInterceptor] as TestCoroutineDispatcher
    
        override fun apply(
            base: Statement,
            description: Description?
        ) = object : Statement() {
    
            override fun evaluate() {
                Dispatchers.setMain(dispatcher)
                base.evaluate()
    
                cleanupTestCoroutines()
                Dispatchers.resetMain()
            }
        }
    }
    

    由于替换了主调度程序,代码将按顺序执行(您的测试代码,然后查看模型代码,然后启动协程)。

    上述方法的优点:

    1. 正常写测试代码,不用runBlocking左右;
    2. 无论何时在协程中发生崩溃,测试都会失败(因为每次测试后都会调用cleanupTestCoroutines())。
    3. 您可以测试内部使用delay 的协程。因为该测试代码应该在coroutineTestRule.runBlockingTest { } 中运行,advanceTimeBy() 用于移动到未来。

    【讨论】:

    • 我的 ViewModel 没有 injectScope
    【解决方案7】:

    我确实使用了帮助模拟 viewModelScope 实例的 mockk 框架,如下所示

    https://mockk.io/

    viewModel = mockk<MyViewModel>(relaxed = true)
    every { viewModel.viewModelScope}.returns(CoroutineScope(Dispatchers.Main))
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 2019-11-19
      • 2018-05-26
      • 2020-09-18
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多