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");
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With