简体   繁体   English

引发异常的PowerMockito调用私有方法失败

[英]PowerMockito call private method that throws Exception fails

I try to mock following method foo in class MyClass : 我尝试在类MyClass模拟以下方法foo

private Class<?> foo(final String str) throws ClassNotFoundException{
    return Class.forName(str);
}

So I wrote: 所以我写道:

MyClass pl = PowerMockito.spy(new MyClass());

try {
    PowerMockito.when(pl, PowerMockito.method(MyClass.class, "foo", String.class))
                .withArguments(anyString())
                .thenReturn(Boolean.TRUE.getClass());
} catch (Exception e) {
    e.printStackTrace(); // catch ClassNotFoundException
}

It doesn't work and throws Exception java.lang.reflect.InvocationTargetException . 它不起作用,并引发异常java.lang.reflect.InvocationTargetException

However, if i'll replace return Class.forName(str) with return Boolean.TRUE.getClass(); 但是,如果我将return Class.forName(str)替换为return Boolean.TRUE.getClass(); in foo method - everything is ok. foo方法中-一切正常。

How to tell to PowerMockito to invoke method foo that throws Exception on failure? 如何告诉PowerMockito调用方法foo ,该方法会在失败时引发Exception?

  1. if you dont need real method call , and you can work with mock - change spy() to mock() 如果您不需要真正的方法调用,并且可以使用模拟-将spy()更改为模拟()

MyClass pl = PowerMockito. MyClass pl = PowerMockito。 spy(new MyClass()) ; 间谍(新的MyClass()) ;

MyClass pl = PowerMockito. MyClass pl = PowerMockito。 mock(MyClass.claa) ; 模拟(MyClass.claa) ;

and your code works without any changes , except spy/mock. 并且您的代码可以正常工作,间谍/模拟除外。

  1. if you need SPY() with real method call 如果您需要带有实际方法调用的SPY()

do this: 做这个:

MyClass pl = PowerMockito.spy(new MyClass()); MyClass pl = PowerMockito.spy(new MyClass());

    try {
        PowerMockito.doReturn(Boolean.TRUE.getClass())
                .when(pl, PowerMockito.method(MyClass.class, "foo", String.class))
                .withArguments(anyString());
    } catch (Exception e) {
        e.printStackTrace(); // catch ClassNotFoundException
    }

However, if i'll replace return Class.forName(str) with return Boolean.TRUE.getClass(); 但是,如果我将return Class.forName(str)替换为return Boolean.TRUE.getClass(); in foo method - everything is ok. 在foo方法中-一切正常。

this works due to 1. it's call a real metho , 2. you retrun Boolean class . 这是由于1.它被称为真正的方法,2.您重新运行Boolean类。 but when you call with anyString() it calls real method and pass null as value. 但是,当您使用anyString()进行调用时,它将调用实型方法并将null作为值传递。

read Important gotcha on spying real objects! 阅读有关监视真实物体的重要提示! :):) :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM