开发者

How to mock a void static method to throw exception with Powermock?

开发者 https://www.devze.com 2023-04-05 22:13 出处:网络
I am trying to use Powermock and Mockito to mock a void static method to 开发者_Python百科throw exception as below. But I met a problem. Unless I make the two invocations of Adder.add() with the same

I am trying to use Powermock and Mockito to mock a void static method to 开发者_Python百科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, 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 
}

Thanks in advance. :)

Answer is as below.

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());


Answer is as below.

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());

EDIT:
Link is dead, try Internet Archive one instead.


Or

PowerMockito.mockStatic(Adder.class);
PowerMockito.doThrow(new IOException()).when(Adder.class, "add", Mathers.eq(12));


Did you forget to put PowerMock in replay mode?

How to Mock Static methods.

Per your link...

How to verify behavior Verification of a static method is done in two steps. First call PowerMockito.verifyStatic() to start verifying behavior and the call the static method you want to verify. E.g.

 PowerMockito.verifyStatic();
 Static.firstStaticMethod(param);

Important: You need to call verifyStatic() per method verification.

0

精彩评论

暂无评论...
验证码 换一张
取 消