0
0
JunitHow-ToBeginner ยท 3 min read

How to Use assertTrue in JUnit for Simple Boolean Tests

Use assertTrue in JUnit to check if a condition is true during a test. It takes a boolean expression and passes the test if the expression is true; otherwise, it fails the test.
๐Ÿ“

Syntax

The assertTrue method is used to verify that a condition is true in a test. It has two common forms:

  • assertTrue(boolean condition): Checks if the condition is true.
  • assertTrue(String message, boolean condition): Checks the condition and shows the message if the test fails.
java
assertTrue(condition);
assertTrue("Failure message", condition);
๐Ÿ’ป

Example

This example shows a simple JUnit test using assertTrue to check if a number is positive.

java
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;

public class NumberTest {

    @Test
    public void testIsPositive() {
        int number = 5;
        assertTrue(number > 0, "Number should be positive");
    }
}
Output
Test passed successfully with no errors.
โš ๏ธ

Common Pitfalls

Common mistakes when using assertTrue include:

  • Passing a non-boolean expression, which causes a compile error.
  • Using assertTrue without a helpful failure message, making debugging harder.
  • Confusing assertTrue with assertEquals for boolean checks.
java
/* Wrong: passing a non-boolean expression */
// assertTrue(5); // Compile error

/* Right: pass a boolean condition */
assertTrue(5 > 0, "5 should be greater than 0");
๐Ÿ“Š

Quick Reference

Remember these tips when using assertTrue:

  • Use it to check boolean conditions.
  • Always add a failure message for clarity.
  • It fails the test if the condition is false.
โœ…

Key Takeaways

Use assertTrue to verify that a condition is true in your test.
Include a failure message to make test failures easier to understand.
assertTrue fails the test if the condition is false.
Pass only boolean expressions to assertTrue to avoid errors.
assertTrue is ideal for simple true/false checks in tests.