【问题标题】:Verify suspend function with Matchers.anyObject()使用 Matchers.anyObject() 验证挂起功能
【发布时间】:2019-01-11 15:26:46
【问题描述】:

我正在尝试将协程添加到我们的 Android 应用程序,但我遇到了我们的模拟框架的障碍。我的界面有一个这样的挂起功能:

interface MyInterface {
  suspend fun makeNetworkCall(id: String?) : Response?
}

这是我尝试验证代码在我的单元测试中执行的方式

runBlocking {
  verify(myInterface).makeNetworkCall(Matchers.anyObject())
}

当我这样做时,我收到以下错误

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at     com.myproject.MyTest$testFunction$1.invokeSuspend(MyTest.kt:66)

This exception may occur if matchers are combined with raw values:
  //incorrect:
  someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
  //correct:
  someMethod(anyObject(), eq("String by matcher"));

在使用协程时,是否有另一种方法可以验证是否调用了适当的方法?任何帮助将不胜感激。

【问题讨论】:

    标签: android junit mockito kotlinx.coroutines


    【解决方案1】:

    我尝试使用您提供的代码编写类似的测试。最初,我得到了和你一样的错误。但是,当我使用 mockito-core v2.23.4 时,测试通过了。

    您可以尝试以下快速步骤:

    1. testCompile "org.mockito:mockito-core:2.23.4" 添加到 build.gradle 文件的依赖项列表中。

    2. 再次运行测试,应该不会出现类似错误。

    由于Matchers.anyObject() 已弃用,我使用了ArgumentMatchers.any()

    下面可以看到客户端代码:

    data class Response(val message: String)
    
    interface MyInterface {
        suspend fun makeNetworkCall(id: String?) : Response?
    }
    
    class Client(val  myInterface: MyInterface) {
        suspend fun doSomething(id: String?) {
            myInterface.makeNetworkCall(id)
        }
    }
    

    这里是测试代码:

    class ClientTest {
        var myInterface: MyInterface = mock(MyInterface::class.java)
    
        lateinit var SUT: Client
    
        @Before
        fun setUp() {
            SUT = Client(myInterface)
        }
    
        @Test
        fun doSomething() = runBlocking<Unit> {
            // Act
            SUT.doSomething("123")
            // Verify
            Mockito.verify(myInterface).makeNetworkCall(ArgumentMatchers.any())
        }
    }
    

    【讨论】:

    • 感谢您的回复。由于某种原因,在运行提供的示例时出现以下错误:java.lang.NoSuchMethodError: org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress()Lorg/mockito/internal/progress/MockingProgress;
    • 这是堆栈跟踪中引用代码的行。在 com.myproject.TestingStuff$doSomething$1.invokeSuspend(TestingStuff.kt:37)
    • 您是否已将 mockito 更新到 v2.23.4?我在 Intellij Idea 和 Android Studio 上都试过了,但我没有得到类似的错误
    • 也许你可以尝试清理和重建?
    • 如果您使用任何其他测试库,错误也可能与此有关。
    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2020-03-13
    • 1970-01-01
    相关资源
    最近更新 更多