Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply conditions set in AssertJ assertions?

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

like image 544
a.k Avatar asked Nov 20 '17 17:11

a.k


People also ask

Should I use AssertJ?

Using AssertJ you can write cleaner and more readable code. Plus it is super easy to learn and use. AssertJ works with any Java version over Java 6, it also supports assertions using the newer features in Java such as lambdas. Find more about methods in AssertJ here.

What is AssertJ in Java?

AssertJ core is a Java library that provides a fluent interface for writing assertions. Its main goal is to improve test code readability and make maintenance of tests easier. AssertJ core provides assertions for JDK standard types and can be used with JUnit, TestNG or any other test framework.

How do you use soft assert in JUnit?

Soft assertions are needed in case of functional tests being run with JUnit. Since such is not available out of the box because JUnit is targeted for unit tests soft assertions can be used from external libraries such as AssertJ.


1 Answers

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.

like image 150
gil.fernandes Avatar answered Sep 20 '22 08:09

gil.fernandes