Group of assertions

An important Jupiter assertion is assertAll. This method allows to group different assertions at the same time. In a grouped assertion, all assertions are always executed, and any failures will be reported together.

The method assertAll accepts a vargargs of lambda expressions (Executable…) or a stream of those (Stream<Executable>). Optionally, the first parameter of assertAll can be a String message aimed to label the assertion group.

Let’s see an example. In the following test, we are grouping a couple of assertEquals using lambda expressions:

package io.github.bonigarcia;

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

import org.junit.jupiter.api.Test;

class GroupedAssertionsTest {

@Test
void groupedAssertions() {
Address address = new Address("John", "Smith");
// In a grouped assertion all assertions are executed, and any
// failures will be reported together.
assertAll("address", () -> assertEquals("John",
address.getFirstName()),
() -> assertEquals("User", address.getLastName()));
}

}

When executing this test, all assertions of the group will be evaluated. Since the second assertion fails (lastname does not match), one failure is reported in the final verdict, as can be seen in the following screenshot:

Console output of grouped assertions example
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.0.85