PowerMockito似乎无法匹配并重载方法 [英] PowerMockito can't seem to match and overloaded method

查看:681
本文介绍了PowerMockito似乎无法匹配并重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
    }
}

模拟设置

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

但是PowerMockito不断返回此错误

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)

我正在将PowerMockito 1.5与Mockito 1.9.5一起使用

I'm using PowerMockito 1.5 with Mockito 1.9.5

推荐答案

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

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.

类似

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

另请参见

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆