Test multiple assertions with argument aggregation in JUnit
Preconditions (2)
✅ Expected Result: All assertions run and failures (if any) are reported together
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class Calculator { public int add(int a, int b) { return a + b; } } public class CalculatorTest { private final Calculator calculator = new Calculator(); @Test void testAddWithArgumentAggregation() { assertAll("Addition tests", () -> assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5"), () -> assertEquals(0, calculator.add(-1, 1), "-1 + 1 should be 0"), () -> assertEquals(0, calculator.add(0, 0), "0 + 0 should be 0") ); } }
This test class defines a simple Calculator with an add method.
The test method testAddWithArgumentAggregation uses assertAll to group three assertions. Each assertion checks the add method with different inputs.
Using assertAll means all assertions run even if some fail, and the test report shows all failures together. This helps find multiple issues in one test run.
Clear messages in assertions help understand which case failed.
Now add data-driven testing with 3 different input pairs and expected sums using @ParameterizedTest
@ArgumentsAggregator in JUnit parameterized tests?public class PersonAggregator implements ArgumentsAggregator {
@Override
public Person aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) {
return new Person(accessor.getString(0), accessor.getInteger(1));
}
}
@ParameterizedTest
@CsvSource({"Alice,30", "Bob,25"})
void testPerson(@AggregateWith(PersonAggregator.class) Person person) {
assertTrue(person.getAge() > 20);
}public class ProductAggregator implements ArgumentsAggregator {
@Override
public Product aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) {
String name = accessor.getString(0);
int price = accessor.getInteger(1);
return new Product(name, price);
}
}
@ParameterizedTest
@CsvSource({"Laptop,1000", "Phone,abc"})
void testProduct(@AggregateWith(ProductAggregator.class) Product product) {
assertNotNull(product);
}Person object with fields name and age. You have CSV data with columns name, age, and city. How can you write a custom aggregator to ignore the city column and only aggregate name and age into Person?Pass the test and this pattern moves unknown