当我测试这个静态方法时
When I'm testing this static method
public class SomeClass {
public static long someMethod(Map map, String string, Long l, Log log) {
...
}
}
与
import org.apache.commons.logging.Log;
@RunWith(PowerMockRunner.class)
//@PrepareForTest(SomeClass.class)
public class Tests {
@Test
public void test() {
...
PowerMockito.mockStatic(SomeClass.class);
Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), isA(Log.class))).thenReturn(1L);
...
}
}
我得到了 InvalidUseOfMatchersException
.我的问题是:
I got InvalidUseOfMatchersException
. My questions are:
isA(Log.class)
返回 null.@PrepareForTest
注释添加到测试类并运行测试时,junit 没有响应.为什么?isA(Log.class)
returns null.@PrepareForTest
annotation to the test class and run the test, the junit makes no response. Why?编辑
我尝试不使用参数匹配器,得到了
I tried not to use argument matchers, and got
org.mockito.exceptions.misusing.MissingMethodInvocationException:when() 需要一个参数,该参数必须是模拟方法调用".例如:when(mock.getArticles()).thenReturn(articles);
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);
此外,出现此错误的原因可能是:
Also, this error might show up because:
你存根其中之一:final/private/equals()/hashCode() 方法.这些方法不能被存根/验证.
在 when() 中,你不会在 mock 上调用方法,而是在其他对象上调用.
inside when() you don't call method on mock but on some other object.
在……
所以这似乎是由于 someMethod
本身.方法中有同步块.我想知道 Powermockito 是否可以模拟这种方法.
So it seems due to the someMethod
itself. There are synchronized block in the method. I'm wondering if Powermockito can mock that kind of method or not.
尝试像这样将 isA() 替换为另一个 any() 调用
Try replacing the isA() to another any() call like this
Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), any(Log.class))).thenReturn(1L);
当您遇到异常时检查您的堆栈跟踪.您是否看到任何 NoClassDefFoundError
报告?我注意到当我没有在我的项目中包含 javassist.jar
时,我遇到了类似的错误.
Check your stacktrace when you get the exception. Are you seeing any NoClassDefFoundError
reported? I noticed when I hadn't included the javassist.jar
in my project I got a similar error to you.
我使用 PowerMockito,这些是我添加到一个全新项目中的 jar,用于运行 @Tom 发布的代码
I use PowerMockito and these are the jars I added to a brand new project to run the code that @Tom posted
检查您是否使用了兼容的 JAR 版本,并检查您的项目类路径中是否存在任何其他冲突的 JAR 总是一个好主意.
Always a good idea to check that you're using compatible JAR versions, and also check if there are any other conflicting JARs in your projects classpath.
这篇关于PowerMockito:使用匹配器模拟静态方法时出现 InvalidUseOfMatchersException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!