We use assertTrue and assertFalse to check if something is true or false in our tests. This helps us make sure our code works as expected.
0
0
assertTrue and assertFalse in JUnit
Introduction
When you want to check if a condition is true, like if a user is logged in.
When you want to confirm a feature is disabled by default (false).
When testing if a list contains an item (true).
When verifying a flag or status is off (false).
When checking if a method returns the expected boolean result.
Syntax
JUnit
assertTrue(condition); assertFalse(condition);
condition is a boolean expression that should be true or false.
If the condition is not what you expect, the test will fail and show an error.
Examples
This checks that the user is logged in. The test passes if
isUserLoggedIn() returns true.JUnit
assertTrue(isUserLoggedIn());
This checks that a feature is not enabled. The test passes if
isFeatureEnabled() returns false.JUnit
assertFalse(isFeatureEnabled());
This checks if the list contains "apple". The test passes if it does.
JUnit
assertTrue(list.contains("apple"));
This checks that the user is not blocked. The test passes if
user.isBlocked() returns false.JUnit
assertFalse(user.isBlocked());
Sample Program
This test checks two simple conditions: it expects isSunny to be true and isRaining to be false. Both assertions should pass.
JUnit
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class SimpleTest { @Test void testConditions() { boolean isSunny = true; boolean isRaining = false; assertTrue(isSunny); assertFalse(isRaining); } }
OutputSuccess
Important Notes
Use clear and simple conditions inside assertTrue and assertFalse for easy understanding.
If an assertion fails, JUnit will report which check failed.
You can add a message as a second argument to explain the failure, like assertTrue(condition, "Must be true").
Summary
assertTrue checks if a condition is true.
assertFalse checks if a condition is false.
They help confirm your code behaves as expected by testing boolean results.