Mockito:InvalidUseOfMatchersException

我有一个执行DNS检查的命令行工具。 如果DNS检查成功,则该命令继续执行进一步的任务。 我正在尝试使用Mockito为此编写unit testing。 这是我的代码:

public class Command() { // .... void runCommand() { // .. dnsCheck(hostname, new InetAddressFactory()); // .. // do other stuff after dnsCheck } void dnsCheck(String hostname, InetAddressFactory factory) { // calls to verify hostname } } 

我使用InetAddressFactory来模拟InetAddress类的静态实现。 这是工厂的代码:

 public class InetAddressFactory { public InetAddress getByName(String host) throws UnknownHostException { return InetAddress.getByName(host); } } 

这是我的unit testing用例:

 @RunWith(MockitoJUnitRunner.class) public class CmdTest { // many functional tests for dnsCheck // here's the piece of code that is failing // in this test I want to test the rest of the code (ie after dnsCheck) @Test void testPostDnsCheck() { final Cmd cmd = spy(new Cmd()); // this line does not work, and it throws the exception below: // tried using (InetAddressFactory) anyObject() doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class)); cmd.runCommand(); } } 

运行testPostDnsCheck()testing例外:

 org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 1 recorded. 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")); 

有关如何解决这个问题的任何input?

错误消息很清楚地概括了解决scheme。 该线

 doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class)) 

当需要使用所有原始值或所有匹配器时,使用一个原始值和一个匹配器。 正确的版本可能会被读取

 doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class)) 

我现在有相同的问题很长一段时间,我经常需要混合匹配器和价值观,我从来没有设法做到这一点与Mockito ….直到最近! 我把这个解决scheme放在这里,希望即使这个post很老,也能帮助别人。

在Mockito中使用Matchers AND values显然是不可能的,但是如果Matcher接受比较一个variables呢? 这将解决问题…实际上有: eq

 when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class))) .thenReturn(recommendedResults); 

在这个例子中,'metas'是一个现有的值列表

这可能对未来有所帮助:Mockito不支持嘲笑“最终”的方法(现在)。 它给了我相同的InvalidUseOfMatchersException

对我来说,解决scheme是将方法中不必是“最终”的部分放在单独的,可访问的和可覆盖的方法中。

查看你的用例的Mockito API 。