public class ClassCauseException {
public void funcA() throws NullPointerException {
throw new NullPointerException("Some NULL message");
}
}
Usually I'll do this:
@Test(expected=NullPointerException.class)
public void testFuncB() {
ClassCauseException c = Mockito.spy(new ClassCauseException());
c.funcA();
}
That will only tells me funcA will throw an NullPointerException. But I couldn't verify whether whether the right message is display. Anyhow there is a more elegant way for this issue. With @Rule, I'm allow to verify whether the display message when an Exception is being thrown. For example, when the following test is execute, I'm expecting an NullPointerException will be throw, and a message The NULL value should be display. Eventually the test will failed due to the actual message Some NULL message is display.public class RuleExceptionTest {
@Rule
public ExpectedException exp = ExpectedException.none();
@Test
public void testFuncA() {
exp.expect(NullPointerException.class);
exp.expectMessage("The NULL value");
ClassCauseException c = new ClassCauseException();
c.funcA();
}
}
This could be useful if I care the type of Exception being thrown and what message is being display.

No comments:
Post a Comment