如何使用Powermock模拟void静态方法抛出异常?

编程入门 行业动态 更新时间:2024-10-28 12:21:13
本文介绍了如何使用Powermock模拟void静态方法抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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.

BTW,我添加了 @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 }

提前致谢。 :)

答案如下。

咨询后 code.google/p/powermock/issues/detail?id= 278 ,实际上上面的Adder.add(12)是设置模拟静态方法的一部分。这意味着在使用参数12调用Adder.add()时,将抛出IOException。这很难理解,对吧? :)所以它应该写成如下。

After consulting here code.google/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());

推荐答案

答案如下。

在此处咨询后 code.google/p/powermock/issues/detail?id=278 ,实际上上面的Adder.add(12)是设置模拟静态方法的一部分。这意味着在使用参数12调用Adder.add()时,将抛出IOException。这很难理解,对吧? :)所以它应该写成如下。

After consulting here code.google/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());

编辑: 链接已死,请尝试互联网档案一个而不是。

更多推荐

如何使用Powermock模拟void静态方法抛出异常?

本文发布于:2023-10-31 03:49:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   抛出   静态   异常   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!