How do I test boolean conditions with assertTrue() and assertFalse()?

Use assertTrue() when you expect a boolean condition to be true, and assertFalse() when you expect it to be false.

They are JUnit assertions, most commonly used in JUnit 5 like this:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class BooleanConditionTest {

    @Test
    void shouldCheckBooleanConditions() {
        String message = "Hello JUnit";

        assertTrue(message.contains("JUnit"));
        assertFalse(message.isEmpty());
    }
}

assertTrue()

assertTrue(condition) passes if the condition evaluates to true.

assertTrue(5 > 3);
assertTrue("JUnit".startsWith("J"));

If the condition is false, the test fails.

assertFalse()

assertFalse(condition) passes if the condition evaluates to false.

assertFalse(5 < 3);
assertFalse("JUnit".isBlank());

If the condition is true, the test fails.

Example with a custom method

Suppose you have a method that checks whether a user is active:

class User {
    private boolean active;

    User(boolean active) {
        this.active = active;
    }

    boolean isActive() {
        return active;
    }
}

You can test it like this:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class UserTest {

    @Test
    void activeUserShouldReturnTrue() {
        User user = new User(true);

        assertTrue(user.isActive());
    }

    @Test
    void inactiveUserShouldReturnFalse() {
        User user = new User(false);

        assertFalse(user.isActive());
    }
}

Add failure messages

You can also provide a message that appears when the assertion fails:

assertTrue(user.isActive(), "User should be active");
assertFalse(message.isEmpty(), "Message should not be empty");

Summary

Assertion Use when you expect
assertTrue(condition) The condition should be true
assertFalse(condition) The condition should be false

In short:

assertTrue(value > 0);
assertFalse(name.isBlank());