Assertions: assertTrue() and assertFalse()
Explore how the assertTrue and assertFalse assertion methods work in JUnit 5 to validate boolean conditions in your tests. Understand various overloaded methods, including those using BooleanSupplier and message suppliers, to write clear and effective unit tests.
What are assertions?
Assertions verify that expected conditions are met. JUnit 5 adds more assertion methods. All JUnit 5 assertions are static methods of the class org.junit.jupiter.Assertions. Some assertions already exist in JUnit 4. These assertions have been updated in JUnit 5. Each assertion has different overloaded methods to accept different parameters.
The assertTrue() method
The assertTrue() method asserts that the given condition is true.
- If the given condition is
true, the test case passes. - If the given condition is
false, the test case fails.
Examples of assertTrue()
It has the following overloaded methods:
-
The
assertTrue(boolean condition)method is the simplest form, which only accepts a single boolean parameter. Examples of this function can be seen in lines 5–9 and 11–15 in the code below. Note that the functiontestAssertTrueWithTrueCondition()passes because it’s passed atruevalue, whereas the functiontestAssertTrueWithFalseCondition()doesn’t pass becausefalseis passed. -
For ...