You could use the @Rule
annotation with ExpectedException
, like this:
@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...
System.out.println("=======Starting Exception process=======");
throw new NullPointerException("Employee ID is null");
}
Note that the example in the ExpectedException
docs is (currently) wrong - there's no public constructor, so you have to use ExpectedException.none()
.