Testing for the expected exception message with junit 5

Niels Basjes :

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?

michalk :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305905&siteId=1