assertj

AssertJ: How to know which condition(s) failed when using allOf()


I am using assertj library for performing assertions in my JUnit5 tests. I want to perform multiple assertions, I was exploring few different ways and got to know about Conditions.

final var condition1 = new Condition<String>(text -> text != null, "Input not null");
final var condition2 = new Condition<String>(text -> text.equalsIgnoreCase("abc"), "Input not matching");
assertThat(someString).satisfies(allOf(condition1, condition2));

When I execute above code, I get below output:

Expecting actual: "PQR"
to satisfy:
all of:[Input not null, Input not matching]

The output doesn't really specify which of the 2 conditions failed. I can use separate statements to assert each condition or as suggested in this question, I could do something like:

assertThat(input).satisfies(text -> {
    assertThat(text).isNotNull();
    assertThat(text).isEqualTo("abc");
});

There is another way to do it using ThrowingConsumer along with andThen as below -

ThrowingConsumer<String> consumer1 = text -> assertThat(text).isNotBlank();
ThrowingConsumer<String> consumer2 = text -> assertThat(text).isEqualTo("abc");
// usage
assertThat(text).satisfies(consumer1.andThen(consumer2));

But I would like to know how to get exact failure message when using allOf().


Solution

  • We could indeed be more informative about the failing condition, in the meantime the suggested satisfies alternative is a good way to get the error message.

    I created https://github.com/assertj/assertj/issues/3537 to track this issue.

    Edit: the issue has been resolved, the error message now looks like enter image description here