Mockito的新手 - 为什么这会给我一个InvalidUseOfMatchers异常的任何想法?我在调用Mockito.verify()时对方法的每个参数都使用了匹配器。验证是在一个接口方法上运行的,我已经让它在具有类似签名的相同接口上使用其他方法,所以我认为我必须遗漏一些明显的东西。
对于后台,这里有几个参与测试的精简应用程序类:
public class QueueEntry {
private String _id;
public QueueEntry(String theId) {
_id = theId;
}
public String getId() { return _id; }
}
public interface IHandler {
public void onError(QueueEntry arg1, String arg2, String arg3);
}
...我正在为IHandler设置一个模拟器,它是被测试类的依赖项,并希望验证' onError'使用Mockito匹配器使用特定参数调用方法。这是我对QueueEntry参数的自定义匹配器(上面接口定义中的arg1):
class EntryMatcher extends BaseMatcher<QueueEntry> {
private QueueEntry _entry = null;
public EntryMatcher(QueueEntry theEntry) {
_entry = theEntry;
}
@Override
public void describeTo(Description description) {
description.appendText("Queue entry id of <" + _entry.getId() + ">");
}
@Override
public boolean matches(Object item) {
QueueEntry theEntry = (QueueEntry)item;
return theEntry.getId().equals(_entry.getId());
}
}
...我正在创建这样的模拟:
IHandler theHandler = Mockito.mock(IHandler.class);
...然后像这样实例化自定义匹配器:
EntryMatcher matchesEntry = new EntryMatcher( anEntryInstance );
......这就是我得到异常的地方
Mockito.verify(theHandler).onError( Mockito.argThat( matchesEntry ),
Mockito.eq( anObject.aMethodReturningAString() ),
Mockito.eq( "Job failed" ) );
...这里是异常追踪:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 0 matchers expected, 1 recorded:
-> at unit.be.publishing.TestCases.testCase(TestCases.java:183)
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"));
For more info see javadoc for Matchers class.