我想测试一下这个方法:
public void some_method(SomeFactory someFactory) {
A a = someFactory.populateWithParameter(parameter1, parameter2, parameter3, parameter4);
a.method_call();
....
}工厂走这条路
public class SomeFactory(){
// some constructor
public A populateWithParameter(SomeClass1 someClass1, SomeClass2 someClass2, String string, int parameter){
return new A(someClass1, someClass2, string, parameter)
}
}测试结果是
public void testSomeMethod() throws Exception {
SomeFactory someFactory = mock(SomeFactory.class);
when(someFactory.populateWithParameter(
any(SomeClass1.class), any(SomeClass2.class),
anyString(), anyInt())).thenReturn(notNull());
mainActivity.some_method(someFactory);
...
}我收到了这个消息
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 1 recorded:发布于 2016-07-19 01:05:32
不允许使用notNull()作为返回值。Mockito匹配器只代表when和verify调用中的参数,不能作为返回值使用。特别是,notNull()实际上将返回null,并将“非null”匹配标记为隐藏堆栈的副作用,它会一直挂起,直到您下次与模拟交互(当您实际调用some_method时)。
尽管您没有列出InvalidUseOfMatchersException的堆栈跟踪,但我敢打赌,错误实际上是在通过some_method调用populateWithParameter时发生的,而不是在存根populateWithParameter时。"1记录的“匹配器是notNull(),其中"4个匹配器预期”指的是方法调用中的参数数量。错误消息实际上是为某些参数忘记使用匹配器的情况量身定做的,比如populateWithParameter(any(), any(), anyString(), 42),这是一个非常常见的错误。
虽然我在评论中看到“它不工作!”当您尝试返回一个实例时,我可以保证返回notNull()绝对会导致问题,而返回一个实例可能只会揭示一个不同的问题。在切换到返回实例后,您可能希望使用完整堆栈跟踪更新您的问题,或者提出新问题。
有关幕后Mockito匹配器的更多信息,请参阅my question/answer here。
https://stackoverflow.com/questions/38405441
复制相似问题