ScreenshotNeo

BlogHow-to

How to Use assertTrue in Java

Use JUnit’s assertTrue to check a boolean condition in Java. See the correct import, message syntax, runnable JUnit Jupiter example, and the JUnit 4 difference.

By the ScreenshotNeo team4 October 20266 min read

In a JUnit Jupiter (JUnit 5) test, statically import assertTrue and pass it a boolean condition. Add an optional failure message after the condition:

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

assertTrue(condition);
assertTrue(condition, "explain what was expected");

JUnit fails the test with an AssertionError when the condition is false. The key version detail: JUnit 4 puts the message before the condition; Jupiter puts it after. Check the imports in your project before copying an example. See the official JUnit Jupiter Assertions API.

1. Add and run a JUnit Jupiter test

For a Maven project, add the JUnit Jupiter dependency. This example uses version 5.14.2, the version documented by the API linked above:

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>5.14.2</version>
  <scope>test</scope>
</dependency>

Save this as src/test/java/example/ValidationTest.java:

package example;

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

import org.junit.jupiter.api.Test;

class ValidationTest {
    @Test
    void resultIsValid() {
        boolean valid = validateResult();
        assertTrue(valid);
    }

    @Test
    void resultHasAtLeastOneEntry() {
        int actualCount = 3;
        assertTrue(actualCount > 0, "expected at least one result");
    }

    private static boolean validateResult() {
        return true;
    }
}

Run the test with mvn test. The class and method do not need to be public for Jupiter. If your project uses Gradle or a different JUnit version, use the dependency and test-runner configuration already established by that project; the assertion syntax still depends on the API imported by the test.

2. Choose the right assertTrue overload

Jupiter provides overloads for a boolean condition and a BooleanSupplier, with optional failure messages. Use the simplest overload that makes the test clear.

Use Jupiter example When it fits
Condition only assertTrue(isReady); The condition already has a useful name.
Condition and literal message assertTrue(count > 0, "expected results"); A short explanation helps identify the failed expectation.
Condition and lazy message assertTrue(valid, () -> buildDiagnostic()); Building diagnostic text is expensive and should happen only on failure.
BooleanSupplier condition assertTrue(() -> resultIsValid()); You need to supply the condition as a boolean-producing function.

The lazy message form takes a Supplier<String>. JUnit retrieves the message when the assertion fails, avoiding unnecessary diagnostic construction on successful runs. Do not confuse that message supplier with the BooleanSupplier condition overload: one supplies the condition and the other supplies the failure text.

A comparison is a valid condition:

assertTrue(actualCount > 0, "expected at least one result");
assertTrue(responseCode >= 200 && responseCode < 300,
        () -> "unexpected response code: " + responseCode);

For tests that fundamentally compare expected and actual values, prefer an assertion such as assertEquals(expected, actual). It communicates the comparison directly and generally gives a more useful failure report than wrapping the comparison in assertTrue.

3. JUnit 4 and Jupiter message order

These APIs have similar names but different packages and method signatures. The import determines which syntax is valid:

Framework Static import Message overload
JUnit 4 org.junit.Assert.assertTrue assertTrue("message", condition)
JUnit Jupiter org.junit.jupiter.api.Assertions.assertTrue assertTrue(condition, "message")

The JUnit 4.12 API documents the message-first signature in its Assert Javadoc. The Jupiter API documents the condition-first overload and supplier-based messages in its Assertions Javadoc. Do not mix an import from one framework with the argument order from the other.

For example, this is JUnit 4 syntax:

import static org.junit.Assert.assertTrue;

assertTrue("expected validation to pass", valid);

And this is Jupiter syntax:

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

assertTrue(valid, "expected validation to pass");

4. Common errors and fixes

Symptom Likely cause Fix
assertTrue cannot be resolved The static import is missing, misspelled, or points to an API not on the test classpath. Add the matching static import and verify the JUnit dependency has test scope and is available to the test runner.
“String cannot be converted to boolean” or a similar argument error The message and condition are in the wrong order for the imported API. JUnit 4: message first. Jupiter: condition first. Confirm the package in the import.
@Test is not recognized or the test is not discovered The annotation import, engine, or build tool configuration does not match the JUnit version. For Jupiter, import org.junit.jupiter.api.Test and ensure the project’s test runner is configured to discover Jupiter tests. For JUnit 4, use org.junit.Test and its configured runner.
The test fails even though the code appears valid The expression passed to the assertion evaluated to false, or the test is checking a different state than intended. Inspect the actual values and state at assertion time. Add a concise diagnostic message or use a more specific assertion for comparisons.
A diagnostic message is slow on passing tests Expensive message construction is evaluated before the assertion call. In Jupiter, use the supplier form: assertTrue(condition, () -> buildDiagnostic()).
Lambda overload does not compile The lambda does not match the selected overload or the project’s JUnit version does not provide that overload. Check the API version and lambda return type. Use a direct boolean expression or a literal message if supplier overloads are unavailable.

5. Practical guidance

  • Assert the behavior the test is meant to protect, not an incidental implementation detail.
  • Use a named boolean when a condition is long or combines several checks; this makes failure location and intent easier to read.
  • Keep messages specific enough to explain the expected result. Avoid repeating the entire condition when the expression already says it clearly.
  • Use a lazy message supplier for costly diagnostics, not for simple fixed strings.
  • Use assertEquals for equality expectations and assertFalse when the intended behavior is that a condition is false.

6. Performance, reliability, and cost

An ordinary assertTrue(boolean) evaluates the Java expression before the method call, then checks its result. Keep expressions deterministic and free of side effects: assertions should observe the behavior under test rather than change it. A BooleanSupplier overload provides a supplier-shaped condition; it does not make unrelated work or external operations inherently reliable.

Failure messages are most useful when stable and actionable. A Jupiter message supplier defers building the text until failure, which can avoid work on passing tests. Tests should not depend on assertion execution to perform setup or cleanup. JUnit itself has no per-assertion charge; runtime and resource costs come from the condition and any diagnostics your code computes.

7. Or skip the browser setup

If your test or workflow also needs website screenshots, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. One GET request can return a PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response identifies the page verdict and billing status in headers.

For example, save a screenshot with cURL:

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp

See the ScreenshotNeo API documentation for request options. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.

8. FAQ

Does assertTrue return a boolean?

No. It is an assertion method. It returns normally when the condition is true and fails the test by throwing an AssertionError when false.

Can I assert a Boolean object that might be null?

Prefer to handle null explicitly before unboxing a Boolean. Passing a null reference where Java must convert it to primitive boolean can throw NullPointerException, which is a different failure from a false assertion.

Should every assertion have a message?

No. Use a message when it adds useful context to the failure. Clear conditions and specific assertion APIs can already provide enough information.

Can I use assertTrue outside a test?

You can call the method from ordinary Java code, but it is designed for assertions in tests. Production checks should use normal control flow and application error handling.