Mockito:InvalidUseOfMatchersException

新手上路,请多包涵

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

 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);
    }
}

这是我的单元测试用例:

 @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 (i.e. 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() 测试:

 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"));

关于如何解决这个问题的任何意见?

原文由 devang 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

错误消息概述了解决方案。线

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

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

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

原文由 Ryan Stewart 发布,翻译遵循 CC BY-SA 4.0 许可协议

我很长一段时间都遇到同样的问题,我经常需要混合 Matchers 和价值观,而我从来没有设法用 Mockito 做到这一点……直到最近!我将解决方案放在这里,希望它能对某人有所帮助,即使这篇文章已经很老了。

显然不可能在 Mockito 中同时使用 Matchers 和值,但是如果有一个 Matcher 接受比较变量怎么办?那将解决问题……事实上有: eq

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

在此示例中,“metas”是现有的值列表

原文由 sam 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题