当我测试这个静态方法时
When I'm testing this static method
public class SomeClass { public static long someMethod(Map map, String string, Long l, Log log) { ... } }with
import org.apachemons.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:
编辑
我试图不使用参数匹配器,得到
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()方法。 这些方法无法进行存根/验证。
当你没有在模拟上调用方法但是在其他一些对象上。
inside when() you don't call method on mock but on some other object.
at ...
所以看起来似乎是由于 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()替换为另一个( )这样打电话
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,这些是我添加到一个全新项目的罐子,用于运行@Tom发布的代码
I use PowerMockito and these are the jars I added to a brand new project to run the code that @Tom posted
- powermock-mockito- 1.4.10-full.jar
- mockito-all-1.8.5.jar
- javassist-3.15.0-GA.jar
- junit-4.8.2.jar
- common-logging-1.1.1.jar
- powermock-mockito-1.4.10-full.jar
- mockito-all-1.8.5.jar
- javassist-3.15.0-GA.jar
- junit-4.8.2.jar
- common-logging-1.1.1.jar
检查您是否使用兼容的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:使用matchers模拟静态方法时得到InvalidUseOfMatchersException
发布评论