【问题标题】:PowerMockito call private method that throws Exception failsPowerMockito调用抛出异常的私有方法失败
【发布时间】:2017-06-29 19:53:26
【问题描述】:

我尝试在 MyClass 类中模拟以下方法 foo

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

所以我写了:

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
}

它不起作用并抛出异常java.lang.reflect.InvocationTargetException

但是,如果我在 foo 方法中将 return Class.forName(str) 替换为 return Boolean.TRUE.getClass(); - 一切正常。

如何告诉PowerMockito 调用方法foo 失败时抛出异常?

【问题讨论】:

    标签: java mockito powermock


    【解决方案1】:
    1. 如果您不需要真正的方法调用,并且可以使用 mock - 将 spy() 更改为 mock()

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

    MyClass pl = PowerMockito.mock(MyClass.claa);

    并且您的代码无需任何更改即可工作,除了间谍/模拟。

    1. 如果您需要 SPY() 和真正的方法调用

    这样做:

    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
        }
    

    但是,如果我将 return Class.forName(str) 替换为 return Boolean.TRUE.getClass();在 foo 方法中 - 一切正常。

    这是因为 1. 它被称为真正的方法,2. 你重新运行 Boolean 类。但是当您使用 anyString() 调用时,它会调用真实方法并将 null 作为值传递。

    阅读Important gotcha on spying real objects! :):)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2015-08-19
      • 2017-09-29
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多