Search⌘ K
AI Features

assertTrue() method

Explore the usage of the assertTrue() method in JUnit 5 assertions to verify that conditions are true during unit testing. Understand the variations of assertTrue with boolean values, messages, and suppliers, and learn how each affects test outcomes. This lesson helps you write robust tests by correctly applying assertTrue in different scenarios.

We'll cover the following...

assertTrue() method

Assertions API provide static assertTrue() method. This method helps us in validating that the actual value supplied to it is true.

  • If the actual value is true then test case will pass.
  • If the actual value is not true then test case will fail.

There are basically six useful overloaded methods for assertTrue:-

Java
public static void assertTrue(boolean condition)
public static void assertTrue(boolean condition, String message)
public static void assertTrue(boolean condition, Supplier<String> messageSupplier)
public static void assertTrue(BooleanSupplier booleanSupplier)
public static void assertTrue(BooleanSupplier booleanSupplier, String message)
public static void assertTrue(BooleanSupplier booleanSupplier, Supplier<String> messageSupplier)
Video thumbnail

Demo

Let’s look into the usage of the above methods:-

JUnit5 (Java 1.8)
package io.educative.junit5;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class AssertTrueDemo {
@Test
public void testAssertTrueWithTrueCondition() {
boolean trueValue = true;
assertTrue(trueValue);
}
@Test
public void testAssertTrueWithFalseCondition() {
boolean falseValue = false;
assertTrue(falseValue);
}
@Test
public void testAssertTrueWithFalseConditionAndMessage() {
boolean falseValue = false;
assertTrue(falseValue, "The actual value is false");
}
@Test
public void testAssertTrueWithFalseConditionAndMessageSupplier() {
boolean falseValue = false;
assertTrue(falseValue, () -> "The actual value is false");
}
@Test
public void testAssertTrueWithBooleanSupplier() {
boolean trueValue = true;
assertTrue(() -> trueValue);
}
@Test
public void testAssertTrueWithBooleanSupplierAndMessage() {
boolean falseValue = false;
assertTrue(() -> falseValue, "The actual value is false");
}
@Test
public void testAssertTrueWithBooleanSupplierAndMessageSupplier() {
boolean falseValue = false;
assertTrue(() -> falseValue, () -> "The actual value is false");
}
}

You can perform code changes to above code widget, run and practice different outcomes.

Run AssertTrueDemo class as JUnit Test.

widget

Explanation -

In AssertTrueDemo class there are 7 @Test methods. These 7 methods demonstrate the working of the above 6 overloaded methods of assertTrue ...