一尘不染

Mockito:InvalidUseOfMatchersException

java

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

关于如何解决这个问题有什么意见吗?


阅读 322

收藏
2020-09-08

共1个答案

一尘不染

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

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

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

doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class))
2020-09-08