PowerMockito can't seem to match and overloade

2019-01-15 16:15发布

问题:

I can't seem to overcome this problem. I'm trying to mock an overloaded method that takes 1 argument

class ClassWithOverloadedMethod {
    private boolean isValid(ClassA a){
        return true;
    }

    private boolean isValid(ClassB B){
        return false;
    }
}

Mock setup

ClassWithOverloadedMethod uut = PowerMockito.spy(new ClassWithOverloadedMethod());
PowerMockito.doReturn(true).when(uut, "isValid", Matchers.isA(ClassB.class));

but PowerMockito keeps returning this error

java.lang.NullPointerException
at java.lang.Class.isAssignableFrom(Native Method)
at org.powermock.reflect.internal.WhiteboxImpl.checkIfParameterTypesAreSame(WhiteboxImpl.java:2432)
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1934)
at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:1025)
at org.powermock.reflect.internal.WhiteboxImpl.findMethodOrThrowException(WhiteboxImpl.java:948)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:882)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:713)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:93)

I'm using PowerMockito 1.5 with Mockito 1.9.5

回答1:

Try using one of the when() methods that accepts a Method object. You can use Whitebox to retrieve the method instance you want by specifying the parameter type which should get around your current issue.

So something like

Method m = Whitebox.getMethod(ClassWithOverloadedMethod.class, ClassB.class);
PowerMockito.doReturn(true).when(uut, m).withArguments(Matchers.any(ClassB.class));

See Also

  • http://powermock.googlecode.com/svn/docs/powermock-1.5.1/apidocs/org/powermock/api/mockito/expectation/PowerMockitoStubber.html#when(java.lang.Class,%20java.lang.reflect.Method)
  • http://powermock.googlecode.com/svn/docs/powermock-1.5.1/apidocs/org/powermock/reflect/Whitebox.html#getMethod(java.lang.Class,%20java.lang.Class...)