問題描述
我正在嘗試使用 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 引發異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!