Kirin Yao Kirin Yao - 2 years ago 245
Java Question

PowerMockito: got InvalidUseOfMatchersException when use matchers mocking static method

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;

public class Tests {
public void test() {
Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), isA(Log.class))).thenReturn(1L);

I got
. My questions are:

  1. Why I got this exception when all the arguments are using matchers? How to solve it? I have debugged it, found the
    returns null.

  2. When I add the
    annotation to the test class and run the test, the junit makes no response. Why?


I tried not to use argument matchers, and got

when() requires an argument which has to be 'a method call on a mock'.
For example:

Also, this error might show up because:

  1. you stub either of: final/private/equals()/hashCode() methods.
    Those methods cannot be stubbed/verified.

  2. inside when() you don't call method on mock but on some other object.

at ...

So it seems due to the
itself. There are synchronized block in the method. I'm wondering if Powermockito can mock that kind of method or not.

Answer Source

Try replacing the isA() to another any() call like this

Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), any(Log.class))).thenReturn(1L);


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.

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download