android - 测试协程中可观察到的场变化

标签 android unit-testing kotlin kotlin-coroutines

我正在编写单元测试,当我在执行暂停功能之前然后之后更改可观察值时,就遇到了这种特殊情况。我想编写一个单元测试,以检查该值是否正确更改了两次。

方法如下:

 fun doSomething() {
            viewModelScope.launch(ioDispatcher) {
                try {
                    viewModelScope.launch(Dispatchers.Main) {
                        commandLiveData.value = Pair(CANCEL_TIMER, null)
                    }
                    isProgress.set(true) //need to test it was set to true in one test
                    checkoutInteractor.doSomethingElse().run {
                        handleResult(this)
                    }
                    isProgress.set(false) //need to test it was set to false here in another test
                } catch (ex: java.lang.Exception) {
                    handleHttpError(ex)
                    isProgress.set(false)
                }
            }
        }

在编写测试时,我调用的是doSomething(),但调用时,我不确定如何在checkoutInteractor.doSomethingElse调用之前检测到该值设置为true,然后再检测为false。

这是我的测试
@Test
    fun `test doSomething enables progress`() {
        runBlockingTest {
            doReturn(Response()).`when`(checkoutInteractor). checkoutInteractor.doSomethingElse()
            viewModel.doSomething()
            assertTrue(viewModel.isProgress.get()) //fails obviously as the value was already set to false after the `doSomethingElse` was executed. 
        }
    }

顺便说一句,isProgress是一个ObservableBoolean

最佳答案

您需要模拟或监视isProgresscheckoutInteractor字段,以记录和验证其方法的执行。

  • isProcesscheckoutInteractor的模拟或 spy 传递到您的类(class)中。
  • 执行doSomething()
  • 验证inOrderset()doSomethingElse()函数

  • 例:
    @Test
    fun `test doSomething enables progress`() {
        runBlockingTest {
            val checkoutInteractor = Mockito.spy(CheckoutInteractor())
            val isProcess = Mockito.spy(ObservableBoolean(true))
            val viewModel = ViewModel(isProcess, checkoutInteractor)
    
            viewModel.doSomething()
    
            val inOrder = inOrder(isProcess, checkoutInteractor)
            inOrder.verify(isProcess).set(true)
            inOrder.verify(checkoutInteractor).doSomethingElse()
            inOrder.verify(isProcess).set(false)
        }
    }
    

    关于android - 测试协程中可观察到的场变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60098269/

    相关文章:

    android - 如何从 Genymotion 设备获取 LogCat

    android - react native android 模拟器问题

    java - MVC 和 Spring MVC 单元测试

    android - 如何使用协程测试加载指示器(TestCoroutineScope 已弃用)?

    kotlin - 带有toList的RxJava flatMap

    android - VSCode中的新Flutter项目。无法解析Kotlin插件

    android - 主页按钮仅在我自己的应用程序处于前台时不起作用

    java - 跟踪鼠标光标android

    javascript - 单元测试 Javascript 匿名函数

    android - Kotlin 版本问题