In JUnit 5 you can use Assertions.assertThrows to assert that a particular Exception is thrown in your test. Example:

A very simple example can be:

@Test
void testExpectedException() {
 
  Assertions.assertThrows(NumberFormatException.class, () -> {
    Integer.parseInt("abc");
  });
 
}

If you are using Junit 4.7 you can use the ExpectedException Rule:

public class SampleTest {
  @Rule
  public final ExpectedException exception = ExpectedException.none();

  @Test
  public void testThrowsNumberFormatException() {
     
    exception.expect(NumberFormatException.class);
    Integer.parseInt("One");
  }
}

Older version of Junit 4 can use:

@Test(expected = NumberFormatException.class)
public void testThrowsNumberFormatException()() {
    Integer.parseInt("One");
}
FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials