Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

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

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, 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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...