【问题标题】:PowerMockito can't seem to match and overloaded methodPowerMockito 似乎无法匹配和重载方法
【发布时间】:2013-07-17 08:55:08
【问题描述】:

我似乎无法克服这个问题。我正在尝试模拟一个需要 1 个参数的重载方法

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

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

模拟设置

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

但 PowerMockito 一直返回此错误

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)

我正在使用 PowerMockito 1.5 和 Mockito 1.9.5

【问题讨论】:

    标签: mockito overloading powermock


    【解决方案1】:

    尝试使用接受 Method 对象的when() 方法之一。您可以使用 Whitebox 通过指定参数 type 来检索您想要的方法实例,该参数应该可以解决您当前的问题。

    类似

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

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多