In this post under JUnit 5, I will show with example the purpose of “assertAll” method.
Pre JUnit 5, If a testcase had multiple assert statements, the testing of that testcase would stop immediately at the first assert statement that fails.
So for example if we have below test method
public void testMethod() {
assert1 statement
assert2 statement
assert3 statement
}
If we execute the above test method and if the assert2 statement fails, the JUnit stops there only and exit. It doesn’t test assert3.
This was default behavior pre JUnit 5.
We can change this now in JUnit 5 with the help of assertAll method.
So we if modify the above code as shown below
public void testMethod() {
assertAll(() -> {
assert1 statement
},
() -> {
assert2 statement
},
() -> {
assert3 statement
});
}
Now when we execute the above test method, and assert2 fails JUnit doesn’t stop there, it will continue and test the assert3 statement also.
After executing all the 3 assert statement it gives summary of all the assert statements that failed.
According to Javadoc, they are 3 overloaded version of “assertAll” method
1) one takes a variable argument of “Executable” functional interface
2) second takes a collection of “Executable” functional interface and
3) third one takes a stream of “Executable” functional interface
you can use any of them.
For our example I have created a “Calculator” class as shown below
Calculator
package package10;
public class Calculator {
private int a, b;
public Calculator(int a, int b) {
this.a = a;
this.b = b;
}
public int add() {
return this.a + this.b;
}
public int substract() {
return this.a - this.b;
}
public int divide() {
return this.a/this.b;
}
}
The test case will be as shown below
Test Case
package package10;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
public void testAssertAll() {
Calculator calculator = new Calculator(10, 2);
assertAll(() -> {
assertEquals(12, calculator.add());
},
() -> {
assertEquals(9, calculator.substract());
},
() -> {
assertEquals(6, calculator.divide());
});
}
}