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.
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");
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With