使用Matchers.anyObject()验证暂停功能

时间:2019-01-11 15:26:46

标签: android junit mockito kotlinx.coroutines

我正在尝试将协程添加到我们的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"));

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

1 个答案:

答案 0 :(得分:1)

我尝试使用您提供的代码编写类似的测试。最初,我遇到了与您相同的错误。但是,当我使用 mockito-core v2.23.4 时,测试已通过。

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

  1. Using "MIBPostProcessDependencyGraph" task from assembly "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets\Microsoft.Build.CppTasks.Common.dll". Task "MIBPostProcessDependencyGraph" To improve incremental build performance for managed components, please make sure that the 'VC++ Directories->Reference Directories' points to all the paths which contain the referenced managed assemblies. Could not load file or assembly 'general.Interop, Version=1.30.21.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. To improve incremental build performance for managed components, please make sure that the 'VC++ Directories->Reference Directories' points to all the paths which contain the referenced managed assemblies. Could not load file or assembly 'Google.ProtocolBuffersLite.Serialization, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589' or one of its dependencies. The system cannot find the file specified. To improve incremental build performance for managed components, please make sure that the 'VC++ Directories->Reference Directories' points to all the paths which contain the referenced managed assemblies. Could not load file or assembly 'Collector2007, Version=3.10.18.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. Done executing task "MIBPostProcessDependencyGraph". Done building target "ManagedIncrementalBuildPostProcessDependencyGraph" in project 添加到build.gradle文件的依赖项列表中。

  2. 再次运行测试,您应该不会遇到类似的错误。

不推荐使用testCompile "org.mockito:mockito-core:2.23.4",因此我使用了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)
    }
}