In this post under JUnit 5, I will introduce you to a new overloaded version of “assertTrue” and “assertFalse” methods.
In the earlier versions, we used to stored the result of a comparison in local variable of type boolean and when calling assertTrue or assertFalse, we used to pass that local variable as an argument to assert methods as shown below
Previous version
boolean comparisonResult = (result % 2 == 0);
assertTrue(comparisonResult, "Assertion Successful");
In the above code snippet, “comparisonResult” stores the result of comparison. At next line it is passed to “assertTrue” method as an argument to assert whether the value is true or false.
Now in the newer overloaded version we can combine both statements in a single statement as shown below
Newer version
assertTrue(() -> {return (result % 2 == 0);}, "Assertion Successful");
The new overloaded version accepts a Supplier Functional Interface as an first argument because of which the above approach is possible.
Below is the method declaration
public static void assertFalse​(BooleanSupplier booleanSupplier, String message)
Below is the complete code for your reference
Class to be tested
package package5;
public class NextEvenNumberGenerator {
public int generate(int value) {
while(true) {
value = value + 1;
if(value % 2 == 0) return value;
}
}
}
In the above code, the “NextEvenNumberGenerator” takes an integer as input and generate even number nearer to it. We will be writing test case to test this “generate” method of “NextEvenNumberGenerator” class
Below is the test class code for your reference.
Test Class
package package5;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class NextEvenNumberGeneratorTest {
@Test
public void testGenerate() {
NextEvenNumberGenerator nextEvenNumberGenerator = new NextEvenNumberGenerator();
int result = nextEvenNumberGenerator.generate(12);
assertTrue(() -> {return (result % 2 == 0);}, "Assertion Successful");
}
}
In this way we can use the new overloaded versions of “assertTrue” and “assertFalse”