[英]PowerMockito: got InvalidUseOfMatchersException when use matchers mocking static method
[英]invalid matchers when mocking
我想测试这种方法:
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:
不允许使用notNull()
作为返回值。 Mockito匹配器仅代表对when
和verify
调用中的参数,不能用作返回值。 特别是, notNull()
实际上会返回null并将“ not null”匹配标记为在隐藏堆栈上的副作用,直到在您与下一个模拟交互之前(当您实际调用some_method
),它都会一直存在。
尽管您没有列出InvalidUseOfMatchersException
堆栈跟踪,但我敢打赌,该错误实际上是在您通过some_method
调用 populateWithParameter
时发生的,而不是在对populateWithParameter
进行存根处理时发生populateWithParameter
。 “记录的1个”匹配器不是notNull()
,其中“预期的4个匹配器”是指方法调用中的参数数量。 错误消息的确是针对以下情况量身定制的:您忘记为某些参数使用匹配器,例如populateWithParameter(any(), any(), anyString(), 42)
,这是一个非常常见的错误。
尽管我在评论中看到“它不起作用!” 当您尝试返回实例时,我可以保证绝对返回notNull()
会引起问题,而返回实例可能只是揭示了一个不同的问题。 切换到返回实例后,您可能想用完整的堆栈跟踪更新问题,或者提出新问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.