Asserting on multiple conditions with AssertJ
Asked Answered
S

2

14

I'm trying to set multiply conditions on the assertJ and could not find in it examplesGit.

I currently write:

    assertThat(A.getPhone())
            .isEqualTo(B.getPhone());
    assertThat(A.getServiceBundle().getId())
            .isEqualTo(B.getServiceBundle().getId());

But want to have something like:

            assertThat(A.getPhone())
            .isEqualTo(B.getPhone())
            .And
            (A.getServiceBundle().getId())
            .isEqualTo(B.getServiceBundle().getId());

As if I use chaining this won't work because I need difference data (id and not phone). is there any possibility to mix it all to a one-assertJ command? It doesn't look like there could be any possibility for this (algorithm wise) but maybe some other idea to && on statements?

Thanks

Stanford answered 20/11, 2017 at 17:15 Comment(0)
S
17

You could use soft assertions with AssertJ to combine multiple assertions and evaluate these in one go. Soft assertions allow to combine multiple assertions and then evaluate these in one single operation. It is a bit like a transactional assertion. You setup the assertion bundle and then commit it.

SoftAssertions phoneBundle = new SoftAssertions();
phoneBundle.assertThat("a").as("Phone 1").isEqualTo("a");
phoneBundle.assertThat("b").as("Service bundle").endsWith("c");
phoneBundle.assertAll();

It is a bit verbose, but it is an alternative to "&&"-ing your assertions. The error reporting is actually quite granular, so that it points to the partial assertions which fail. So the example above will print:

org.assertj.core.api.SoftAssertionError: 
The following assertion failed:
1) [Service bundle] 
Expecting:
 <"b">
to end with:
 <"c">

Actually this is better than the "&&" option due to the detailed error messages.

Statolith answered 20/11, 2017 at 18:17 Comment(0)
B
6

An alternative to assertJ's SoftAssertions is JUnit's assertAll:

import static org.junit.jupiter.api.Assertions.assertAll;

assertAll(
  () -> assertThat("a").as("Phone 1").isEqualTo("a"),
  () -> assertThat("b").as("Service bundle").endsWith("c")
);
Bight answered 27/5, 2022 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.