Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertJ assert on the cause message

Is there a way when using AssertJ agains a method throwing an excetion to check that the message in the cause is equal to some string.

I'm currently doing something like:

assertThatThrownBy(() -> SUT.method())
            .isExactlyInstanceOf(IllegalStateException.class)
            .hasRootCauseExactlyInstanceOf(Exception.class);

and would like to add an assertion to check the message in the root cause.

like image 993
stikku Avatar asked Aug 14 '16 14:08

stikku


2 Answers

Not exactly, the best you can do at the moment is using hasStackTraceContaining, example

Throwable runtime = new RuntimeException("no way", 
                                         new Exception("you shall not pass"));

assertThat(runtime).hasCauseInstanceOf(Exception.class)
                   .hasStackTraceContaining("no way")
                   .hasStackTraceContaining("you shall not pass");
like image 143
Joel Costigliola Avatar answered Sep 24 '22 21:09

Joel Costigliola


Since AssertJ 3.16, two new options are available:

  • getCause():
Throwable runtime = new RuntimeException("no way", 
                                         new Exception("you shall not pass"));

assertThat(runtime).getCause()
                   .hasMessage("you shall not pass");
  • getRootCause():
Throwable rootCause = new RuntimeException("go back to the shadow!");
Throwable cause = new Exception("you shall not pass", rootCause);
Throwable runtime = new RuntimeException("no way", cause);

assertThat(runtime).getRootCause()
                   .hasMessage("go back to the shadow!");

Since AssertJ 3.14, extracting with InstanceOfAssertFactory could be used:

Throwable runtime = new RuntimeException("no way", 
                                         new Exception("you shall not pass"));

assertThat(runtime).extracting(Throwable::getCause, as(THROWABLE))
                   .hasMessage("you shall not pass");

as() is statically imported from org.assertj.core.api.Assertions and THROWABLE is statically imported from org.assertj.core.api.InstanceOfAssertFactories.

like image 26
Stefano Cordio Avatar answered Sep 25 '22 21:09

Stefano Cordio