The rule just has to be defined once, and then can be reused wherever wanted. The expectMessage function just makes a substring search, so you do not need to have to provide the complete error message.@Rule public ExpectedException thrown = ExpectedException.none(); @Test public void throwsNullPointerExceptionWithMessage() { thrown.expect(NullPointerException.class); thrown.expectMessage("Exception Message"); // test code goes here }
In JUnit < 4, the testing is more complex:
@Test public void throwsNullPointerExceptionWithMessage() { boolean exceptionThrown = false; try { // test code goes here } catch (Exception e) { exceptionThrown = true; Assert.assertEquals("Not expected exection type", NullPointerException.class, e.getClass()); Assert.assertTrue("Not expected error message", e.getMessage().contains("Exception Message")); } Assert.assertTrue("Expected exception not thrown", exceptionThrown); }
Keine Kommentare:
Kommentar veröffentlichen