0
0
JUnittesting~15 mins

assertTrue and assertFalse in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify boolean conditions using assertTrue and assertFalse in JUnit
Preconditions (2)
Step 1: Call the method that returns true and verify the result using assertTrue
Step 2: Call the method that returns false and verify the result using assertFalse
✅ Expected Result: The test passes when assertTrue confirms the condition is true and assertFalse confirms the condition is false
Automation Requirements - JUnit 5
Assertions Needed:
assertTrue to verify a condition is true
assertFalse to verify a condition is false
Best Practices:
Use descriptive test method names
Keep tests independent and simple
Use static imports for assertions for readability
Automated Solution
JUnit
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.

Common Mistakes - 4 Pitfalls
Using asserttrue with a false condition
Using assertfalse with a true condition
Not providing a failure message in assertions
Mixing asserttrue and assertfalse on the same condition without clear logic
Bonus Challenge

Now add data-driven testing with 3 different numbers to check even and odd using assertTrue and assertFalse

Show Hint