Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powermock/mockito does not throw exception when told to

I would have assumed that the following test should pass, but the exception is never thrown. Any clues ?

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticService.class)
public class TestStuff {

    @Test(expected = IllegalArgumentException.class)
    public void testMockStatic() throws Exception {
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(StaticService.say("hello"));
        verifyStatic();
        StaticService.say("hello");
}

}

like image 359
Jan-Olav Eide Avatar asked Feb 19 '13 09:02

Jan-Olav Eide


1 Answers

It's because you are using the doThrow...when syntax incorrectly for static methods. There are a couple different ways to approach this which I've outlined in two separate test methods below.

@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticService.class})
public class StaticServiceTest {

    @Test (expected = IllegalArgumentException.class)
    public void testMockStatic1() throws Exception {
        String sayString = "hello";
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(
            StaticService.class, "say", Matchers.eq(sayString));
        StaticService.say(sayString);
        fail("Expected exception not thrown.");
    }

    @Test (expected = IllegalArgumentException.class)
    public void testMockStatic2() throws Exception {
        String sayString = "hello";
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(
            StaticService.class);
        StaticService.say(Matchers.eq(sayString)); //Using the Matchers.eq() is
                                                   //optional in this case.

        //Do NOT use verifyStatic() here. The method hasn't actually been
        //invoked yet; you've only established the mock behavior. You shouldn't
        //need to "verify" in this case anyway.

        StaticService.say(sayString);
        fail("Expected exception not thrown.");
    }

}

For reference, here was the StaticService implementation I created. I don't know if it matches yours but I did verify that the tests pass.

public class StaticService {
    public static void say(String arg) {
        System.out.println("Say: " + arg);
    }
}

See Also

  • http://static.javadoc.io/org.powermock/powermock-api-mockito/1.6.5/org/powermock/api/mockito/expectation/PowerMockitoStubber.html
  • https://github.com/jayway/powermock/wiki/MockitoUsage#how-to-stub-void-static-method-to-throw-exception
like image 68
Matt Lachman Avatar answered Sep 25 '22 02:09

Matt Lachman