Testing Exceptions

JUnit 4

There are two options to test an exception with JUnit 4.

Annotation

@Test(expected = Exception.class)
public final void testWithException() {
   service.throwsException();
}

Rule

@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public final void testWithException() {
   expectedEx.expect(Exception.class);
   expectedEx.expectMessage("error.message");

   service.throwsException();
}

JUnit 5

Thrown Exception

Exception Content

Last updated

Was this helpful?