13

I have a project where I have tests where I deliberately cause a problem and then verify the code responds the way I want it. For this I want to be sure the exceptions not only are the right class but they must also carry the right message.

So in one of my existing (junit 4) tests I have something similar to this:

public class MyTests {
  @Rule
  public final ExpectedException expectedEx = ExpectedException.none();

  @Test
  public void testLoadingResourcesTheBadWay(){
    expectedEx.expect(MyCustomException.class);
    expectedEx.expectMessage(allOf(startsWith("Unable to load "), endsWith(" resources.")));
    doStuffThatShouldFail();
  }
}

I'm currently looking into fully migrating to junit 5 which no longer supports the @Rule and now has the assertThrows that seems to replace this.

What I have not been able to figure out how to write a test that not only checks the exception(class) that is thrown but also the message attached to that exception.

What is the proper way to write such a test in Junit 5?

1
  • 2
    assertThrows returns an exception so you can invoke getMessage on the returned instance and make asserts on this message. Sep 30, 2019 at 8:19

2 Answers 2

22

Since Assertions.assertThrows returns instance of your exception you can invoke getMessage on the returned instance and make assertions on this message :

Executable executable = () -> sut.method(); //prepare Executable with invocation of the method on your system under test

Exception exception = Assertions.assertThrows(MyCustomException.class, executable); // you can even assign it to MyCustomException type variable
assertEquals(exception.getMessage(), "exception message"); //make assertions here
6

Thanks to @michalk and one of my colleagues this works:

Exception expectedEx = assertThrows(MyCustomException.class, () ->
    doStuffThatShouldFail()
);
assertTrue(expectedEx.getMessage().startsWith("Unable to load "));
assertTrue(expectedEx.getMessage().endsWith(" resources."));

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.