Verify boolean conditions using assertTrue and assertFalse in JUnit
Preconditions (2)
✅ Expected Result: The test passes when assertTrue confirms the condition is true and assertFalse confirms the condition is false
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; public class BooleanConditionTest { // Method that returns true public boolean isEven(int number) { return number % 2 == 0; } // Method that returns false public boolean isOdd(int number) { return number % 2 == 0; } @Test public void testAssertTrue() { // 4 is even, so isEven should return true assertTrue(isEven(4), "Expected 4 to be even"); } @Test public void testAssertFalse() { // 5 is odd, so isOdd should return false (since it returns true for even) assertFalse(isOdd(5), "Expected 5 to be odd, so isOdd should be false here"); } }
This test class has two methods: isEven returns true if a number is even, and isOdd incorrectly returns true if a number is even (to demonstrate assertFalse).
The testAssertTrue method uses assertTrue to check that isEven(4) returns true because 4 is even.
The testAssertFalse method uses assertFalse to check that isOdd(5) returns false because 5 is odd and isOdd returns true only for even numbers (so it returns false for 5).
Static imports make the assertions easier to read. Each test has a clear message to explain failure if it happens.
Now add data-driven testing with 3 different numbers to check even and odd using assertTrue and assertFalse
assertTrue(condition) check in a test?assertTrue is designed to verify that a given boolean condition is true during a test.assertFalse which checks for false, assertTrue specifically expects the condition to be true.isValid is false in JUnit?isValid is false, we use assertFalse with the variable directly.assertFalse(isValid); correctly asserts the variable is false. Other options use the wrong assertion method or incorrect comparisons that fail to properly verify the variable is false.boolean isActive = (5 > 3);
assertTrue(isActive);
assertFalse(isActive == false);
5 > 3 is true, so isActive is true.assertTrue(isActive); passes because isActive is true.assertFalse(isActive == false); also passes because isActive == false is false, so assertFalse(false) passes.boolean isReady = false;
assertTrue(isReady);
isReady is set to false.assertTrue(isReady); expects the condition to be true, but it is false, so the assertion fails.isEmpty(String s) returns false when the string is not empty. Which assertion correctly tests this?isEmpty("hello") should return false because the string is not empty.assertFalse(isEmpty("hello")); which passes if the method returns false.Pass the test and this pattern moves unknown