AssertJ assert on the cause message
Asked Answered
B

2

12

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.

Bullpen answered 14/8, 2016 at 14:48 Comment(0)
C
17

AssertJ 3.23

  • 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");
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!");

AssertJ 3.16

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!");

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.

Cartelize answered 6/2, 2020 at 11:16 Comment(0)
S
15

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");
Swirsky answered 15/8, 2016 at 10:39 Comment(1)
Consider using getCause() if your version is >= 3.16 as suggested by Stefano CordioSwirsky

© 2022 - 2024 — McMap. All rights reserved.