How to mock a void static method to throw exception with Powermock?(如何模拟 void 静态方法以使用 Powermock 引发异常?)
问题描述
我正在尝试使用 Powermock 和 Mockito 来模拟 void 静态方法来抛出异常,如下所示.但是我遇到了一个问题.除非我使用相同的参数对 Adder.add() 进行两次调用,否则不会抛出模拟的 IOException
.
I am trying to use Powermock and Mockito to mock a void static method to throw exception as below. But I met a problem. Unless I make the two invocations of Adder.add() with the same argument, the mocked IOException
won't be thrown.
顺便说一句,我已将 @RunWith(PowerMockRunner.class)
和 @PrepareForTest(Adder.class)
添加到单元测试类中.
BTW, I've added @RunWith(PowerMockRunner.class)
and @PrepareForTest(Adder.class)
to the unit test class.
class Adder{
public static void add(int i) throws IOException{
return;
}
}
@Test
public void testAdder() throws IOException{
PowerMockito.mockStatic(Adder.class);
PowerMockito.doThrow(new IOException()).when(Adder.class);
Adder.add(12);
try {
Adder.add(11);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// assert things
}
提前致谢.:)
答案如下.
在这里咨询后http://code.google.com/p/powermock/issues/detail?id=278 ,其实上面的 Adder.add(12) 就是设置 mock 静态方法的一部分.这意味着当使用参数 12 调用 Adder.add() 时,将抛出 IOException.这很难理解,对吧?:) 所以应该写成下面这样.
After consulting here http://code.google.com/p/powermock/issues/detail?id=278 , in fact Adder.add(12) above is part of setting up mock static method. It means when invoking Adder.add() with argument 12, IOException will be thrown. It is hard to understand, right? :) So it should be written as below.
PowerMockito.mockStatic(Adder.class);
PowerMockito.doThrow(new IOException()).when(Adder.class);
Adder.add(anyInt());
推荐答案
答案如下.
在这里咨询后http://code.google.com/p/powermock/issues/detail?id=278 ,其实上面的 Adder.add(12) 就是设置 mock 静态方法的一部分.这意味着当使用参数 12 调用 Adder.add() 时,将抛出 IOException.这很难理解,对吧?:) 所以应该写成下面这样.
After consulting here http://code.google.com/p/powermock/issues/detail?id=278 , in fact Adder.add(12) above is part of setting up mock static method. It means when invoking Adder.add() with argument 12, IOException will be thrown. It is hard to understand, right? :) So it should be written as below.
PowerMockito.mockStatic(Adder.class);
PowerMockito.doThrow(new IOException()).when(Adder.class);
Adder.add(anyInt());
链接已失效,请尝试 Internet Archive 一个.
这篇关于如何模拟 void 静态方法以使用 Powermock 引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何模拟 void 静态方法以使用 Powermock 引发异常?


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01