java - 任何(MyClass.class)实际上只匹配传递类类型的类?

标签 java unit-testing testing mocking mockito

我有以下代码:

verify(javaCompiler, times(1)).writeJavaAndCompile(any(ContractCompilationUnit.class), eq(outputDirectory));
verify(javaCompiler, times(1)).writeJavaAndCompile(any(ParamCompilationUnit.class), eq(outputDirectory));       

我的代码如下:

javaCompiler.writeJavaAndCompile(new ContractCompilationUnit(), outputDirectory);
javaCompiler.writeJavaAndCompile(new ParamCompilationUnit(), outputDirectory);

代码失败,因为第一次验证似乎发现有 2 次调用 javaCompiler.writeJavaAndCompile()。它没有意识到只有一个 ContractCompilationUnit 类型的调用。

避免这种行为的标准程序是什么(除了必须编写我自己的匹配器)?

最佳答案

documentation显示这是已知行为:

Any kind object, not necessary of the given class. The class argument is provided only to avoid casting. Sometimes looks better than anyObject() - especially when explicit casting is required

Alias to anyObject()

This method don't do any type checks, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.

看起来您应该改用 isA:

verify(javaCompiler).writeJavaAndCompile(isA(ContractCompilationUnit.class),
                                         eq(outputDirectory));

关于java - 任何(MyClass.class)实际上只匹配传递类类型的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9358308/

相关文章:

ruby-on-rails - 条件代码 if-else 的 Rspec?

asp.net - 网络测试软件

Java:如何从字符串中提取两个字符之间的子字符串?

java - 如何在java中的jtable中的特定行添加复选框?

java - 是否有与 NUnit 的 TestCaseAttribute 等效的 JUnit?

unit-testing - iOS 中的 XCTest 和 UI 测试

.net - "dotnet test": how to run xunit tests projects in parallel?

java - 安全异常:权限被拒绝

java - EasyMock - 你必须在测试后重置()模拟吗?

javascript - 从默认导入开 Jest 模拟异步函数