Gangmax Blog

How to assert exception message in JUnit?

From here, here and here.

1
2
3
4
5
6
7
8
9
@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("Employee ID is null");
// do something that should throw the exception...
}

Comments