Close

AssertJ - Optional Assertions

[Last Updated: Mar 3, 2026]

Java's Optional is a container object used to represent a possibly-absent value. When testing methods that return Optional, AssertJ provides dedicated assertions that clearly communicate whether a value is expected to be present or absent, and what its value should be.

Why Dedicated Optional Assertions?

Without AssertJ, asserting an Optional might involve assertTrue(opt.isPresent()) followed by assertEquals("foo", opt.get()) — two steps, plus potential NoSuchElementException risk. AssertJ's hasValue() does both safely in one call.

Key Methods

isPresent, isEmpty (absent), hasValue, contains, containsInstanceOf, hasValueSatisfying.

Example

package com.logicbig.example;

import org.junit.jupiter.api.Test;

import java.util.Optional;
import static org.assertj.core.api.Assertions.*;

public class OptionalAssertionsExample {

    @Test
    void myTest() {
        Optional<String> present = Optional.of("hello");
        Optional<String> empty = Optional.empty();

        // presence
        assertThat(present).isPresent();
        assertThat(empty).isEmpty();
        System.out.println("Presence checks passed");

        // exact value
        assertThat(present).hasValue("hello");
        System.out.println("hasValue passed");

        // contains (alias for hasValue)
        assertThat(present).contains("hello");
        System.out.println("contains passed");

        // custom condition on the wrapped value
        assertThat(present).hasValueSatisfying(s -> {
            assertThat(s).startsWith("he").hasSize(5);
        });
        System.out.println("hasValueSatisfying passed");
    }
}

Output

$ mvn clean test -Dtest=*
[INFO] Scanning for projects...
[INFO]
[INFO] ----------< com.logicbig.example:assertj-optional-assertions >----------
[INFO] Building assertj-optional-assertions 1.0-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- clean:3.2.0:clean (default-clean) @ assertj-optional-assertions ---
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ assertj-optional-assertions ---
[INFO] skip non existing resourceDirectory D:\example-projects\assertj\assertj-optional-assertions\src\main\resources
[INFO]
[INFO] --- compiler:3.11.0:compile (default-compile) @ assertj-optional-assertions ---
[INFO] No sources to compile
[INFO]
[INFO] --- resources:3.3.1:testResources (default-testResources) @ assertj-optional-assertions ---
[INFO] skip non existing resourceDirectory D:\example-projects\assertj\assertj-optional-assertions\src\test\resources
[INFO]
[INFO] --- compiler:3.11.0:testCompile (default-testCompile) @ assertj-optional-assertions ---
[INFO] Changes detected - recompiling the module! :source
[INFO] Compiling 1 source file with javac [debug target 17] to target\test-classes
[INFO]
[INFO] --- surefire:3.2.5:test (default-test) @ assertj-optional-assertions ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.logicbig.example.OptionalAssertionsExample
Presence checks passed
hasValue passed
contains passed
hasValueSatisfying passed
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.079 s -- in com.logicbig.example.OptionalAssertionsExample
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.298 s
[INFO] Finished at: 2026-03-03T13:37:20+08:00
[INFO] ------------------------------------------------------------------------

Conclusion

The output confirms presence and value checks on both populated and empty Optionals. hasValueSatisfying demonstrates how to apply a custom condition to the wrapped value — a powerful approach when the exact value is computed and you need to assert on its properties rather than an equality check.

Example Project

Dependencies and Technologies Used:

  • assertj-core 3.27.7 (Rich and fluent assertions for testing in Java)
  • junit-jupiter-engine 6.0.2 (Module "junit-jupiter-engine" of JUnit)
  • JDK 17
  • Maven 3.9.11

AssertJ - Optional Assertions Select All Download
  • assertj-optional-assertions
    • src
      • test
        • java
          • com
            • logicbig
              • example
                • OptionalAssertionsExample.java

    See Also

    Join