In this post under JUnit 5, I will show with example, the new version of assert method which takes a Supplier interface implementation as an argument.
In previous versions of JUnit, we have seen variety of assert methods, which takes the below arguments.
1) The expected value (optional)
2) The actual value (required)
3) String message when the assert fails. (optional)
The string message is created and stored in memory in a String object regardless of whether the assert fails or not.
In JUnit 5, we can postpone the creation of String message until the assert runs and fails. This can be achieved by the help of Supplier interface.
JUnit 5 has added a new assert methods that takes an implementation of Supplier interface as an argument in place of String message.
As a result of which, the Supplier implementation is executed only when assert fails. The Supplier interface implementation should return a String. The returned string will be used
as message to be displayed.
For our example, we will create the below class to be tested
Calculator
package package2;
public class Calculator {
private int x, y;
public int add() {
return x + y;
}
public int sub() {
return x - y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
The test class is as shown below
1 package package2;
2
3 import static org.junit.jupiter.api.Assertions.assertEquals;
4
5 import org.junit.jupiter.api.Test;
6
7 class CalculatorTest {
8
9 private Calculator calculator = new Calculator();
10
11 @Test
12 void testAdd() {
13 calculator.setX(5);
14 calculator.setY(10);
15
16 assertEquals(15, calculator.add(), () -> "Value should be 15");
17 }
18 }
In the above test class, at line 9, I create an instance of Calculator class whose methods has to be tested.
At line 13 and 14, I set the X and Y variable of Calculator instance.
At line 16, I call assertEquals method passing the expected value, the actual value, and a lambda expression for Supplier interface.
So when the assertEquals passes, the Supplier implementation is not called but when the assertEquals fails, the Supplier implementation is called.