Using AssertJ to Verify a Complex Exception

9:01 AM 0 Comments

AssertJ just went up another notch in my book today

For a particular unit test, I needed to verify the contents of an exception. Originally, I figured said contents where just part of the exception message:


assertThatCode(() -> doMyExceptionalThing())
    .isInstanceOf(SomeException.class)
    .hasMessage("This is the error message")


However, that assertion failed because, in the case that this particular exception has a cause, it has two messages to pick from (more on that in a moment) and it chooses the message from the cause instead of the message I wanted.

I could do something like this to get it to work:


try {
    doMyExceptionalThing();
} catch ( SomeException ex ) {
    ErrorDomainObject o = ex.getError();

    // this is the description I need,
    // not the cause's description!
    assertThat(o.getDescription())
        .isEqualTo("This is the error message");
}


But that would break my heart. (And we wouldn't want that... just to clarify)

So, I tried some of AssertJ's matching features:


assertThatCode(() -> doMyExceptionalThing())
    .isInstanceOf(SomeException.class)
    .matches(ex -> "This is the error message"
        .equals(
            ((SomeException) ex)
                .getError()
                .getDescription()));


Yuck!

And then, I came upon hasFieldOrPropertyWithValue. Hmm...

Could something like this possibly work?


assertThatCode(() -> doMyExceptionalThing())
    .isInstanceOf(SomeException.class)
    .hasFieldOrPropertyWithValue(
        "error.description",
        "This is the error message");


And it did! All hail AssertJ for helping me create a clean, readable assertion, even in this slightly more complex scenario.

Josh Cummings

"I love to teach, as a painter loves to paint, as a singer loves to sing, as a musician loves to play" - William Lyon Phelps

0 comments: