Mockito: InvalidUseOfMatchersException

2022-08-31 06:53:09

我有一个执行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"));

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


答案 1

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

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

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

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

答案 2

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

在 Mockito 中,显然不可能同时使用 Matchers 和值,但是如果有 Matcher 接受比较变量呢?这将解决问题...事实上有:eq

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

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


推荐