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.
cause()
is favored over getCause()
:Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).cause()
.hasMessage("you shall not pass");
rootCause()
is favored over 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).rootCause()
.hasMessage("go back to the shadow!");
Two new options are available:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).getCause()
.hasMessage("you shall not pass");
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!");
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
.