gpt4 book ai didi

mockito - PowerMockito 似乎无法匹配和重载方法

转载 作者:行者123 更新时间:2023-12-03 07:50:23 26 4
gpt4 key购买 nike

我似乎无法克服这个问题。我正在尝试模拟一个带有 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

最佳答案

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

所以像

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

也可以看看
  • 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...)
  • 关于mockito - PowerMockito 似乎无法匹配和重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695356/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com