Skip to content
Advertisement

How to show all the failures in Junit Assertions

My requirement is to show all the failures after Junit test run.

I tried two things:

Assertions.assertEquals –> This stops the execution after first failure, and in test report I see only first failure.

Assertions.assertEquals(expceted, actual,"Error Message");

assertj.SoftAssertions –> Here execution happens but in test report I do not see any failure message.

SoftAssertions softAssertions = new SoftAssertions();
softAssertions.assertThat(expected).withFailMessage("Error Message", actual) ;
                   

Any Idea if any other type of assertion or any other option I can use with these assertions?

I tried Junit5 assertAll

for (int index = 0; index < response1.row.size(); index++)
        {
            int finalIndex = index;
            Assertions.assertAll(
                    () ->Assertions.assertEquals(Response1.row.get(finalIndex).field1, Response2.row.get(finalIndex).field1,
                            "Value doesn't match between source and target"),
                    () ->Assertions.assertEquals(Response1.row.get(finalIndex).field2, Response2.row.get(finalIndex).field2,
                            "Value doesn't match between source and target"),
                    () ->Assertions.assertEquals(Response1.row.get(finalIndex).field3, Response2.row.get(finalIndex).field3,
                            "Value doesn't match between source and target")
        }

But here it shows failures only for first row, not for all the rows.

Thanks in advance !!!

Advertisement

Answer

JUnit 5 added assertAll:

assertAll(
        () -> assertEquals(...),
        () -> assertTrue(...)
        // etc
);

It takes any number of lambdas, and if I recall correctly each lambda can even throw exceptions. That means you can delegate to methods:

assertAll(
        ...
        complexAssertion(...)
);

...

private void complexAssertion(...) throws IOException {
    String expectedOutput = <read resource>;
    SomeException thrown = assertThrows(SomeException.class, () -> ...);
    assertInstanceOf(SomeOtherException.class, thrown.getCause());
    // nested assertAll can also be used!
}

Edit: using assertAll inside assertAll, made difficult because of the index:

// assuming that response1.row and response2.row have equal sizes
assertAll(IntStream.range(0, reponse1.row.size())
        .mapToObj(index -> () -> {
            assertAll(
                assertEquals(response1.row.get(index).field1, response2.row.get(index).field1, "message");
                // etc
            );
        })
);

The mapToObj may need a cast to Execution, perhaps extracted to another method.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement