我有一个命令行工具来执行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"));对如何解决这个问题有什么建议吗?
发布于 2013-02-13 11:03:32
错误消息概述了解决方案。这条线
doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class))当需要使用所有原始值或所有匹配器时,使用一个原始值和一个匹配器。正确的版本可能是
doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class))发布于 2015-06-01 20:55:18
很长一段时间我都有同样的问题,我经常需要混合Matcher和values,但我从来没有用Mockito做到这一点……直到最近!我把解决方案放在这里,希望它能帮助一些人,即使这篇文章已经很老了。
显然,在Mockito中同时使用Matcher和values是不可能的,但如果Matcher接受比较变量呢?问题就解决了..。事实上,确实有:eq
when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
.thenReturn(recommendedResults);在本例中,'metas‘是一个现有的值列表
发布于 2017-01-26 21:40:19
它可能会在未来对某些人有所帮助: Mockito现在不支持对'final‘方法的模仿。它给了我相同的InvalidUseOfMatchersException。
对我来说,解决方案是将方法中不一定是“final”的部分放在一个单独的、可访问和可重写的方法中。
查看您的用例的Mockito API。
https://stackoverflow.com/questions/14845690
复制相似问题