Advertise with us

Search Mastertheboss

Our eBooks

How to assert Exceptions in JUnit

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:

void testExpectedException() {
  Assertions.assertThrows(NumberFormatException.class, () -> {

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

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

  public void testThrowsNumberFormatException() {

Older version of Junit 4 can use:

@Test(expected = NumberFormatException.class)
public void testThrowsNumberFormatException()() {
© 2020 All Rights Reserved.

Please publish modules in offcanvas position.