Search code examples
javaunit-testingjunitassertj

AssertJ dynamically check if Optinal is empty or present


I'm working with OptionalAssert class of AssertJ and I need to implement a JUnit ParameterizedTest that will check for presence or emptiness of an Optional instance in a dynamic way:

@ParameterizedTest
@MethodSource(/* values */)
void test_presence(Optional<String> opt, boolean empty) {
    assertThat(opt) // -> .isPresent() / .isEmpty();
}

In a non-parametrised test I would use .isPresent() or .isEmpty() methods to execute the check, but in this case I'd like to apply something like .isPresent(true/false).

I can't find a method like this in the JavaDoc so I'm wondering if there is an alternative approach to this (or should I just deal with an if/else?)

UPDATE I know that I could implement something like so (as suggested in an answer):

assertThat(opt.isPresent()).isEqualTo(present);

but I'd like to maintain a fluent approach, and code similar to this:

assertThat(opt)
    .isPresent(present) // true/false
    .hasValueSatisfying(...)
    .hasValueSatisfying(...)
    // etc.

Solution

  • You can use boolean assert instead

    assertThat(opt.isEmpty()).isEqualTo(empty)
    

    You can use two asserts instead of one, but for fluent assert you can use org.assertj.core.api.Condition.

      @ParameterizedTest
      @MethodSource("t")
      public void test(boolean empty, Object obj) {
        Condition<Optional<Object>> condition = new Condition<>(empty ? Optional::isEmpty : Optional::isPresent,
            "empty=%s", empty);
        assertThat(Optional.ofNullable(obj)).is(condition);
      }
    
      public static Stream<Arguments> t() {
        return Stream.of(Arguments.of(false, new Object()), Arguments.of(true, null), Arguments.of(true, new Object()));
      }
    

    On assertion error following message is shown

    java.lang.AssertionError: 
    Expecting:
      Optional[java.lang.Object@28bdbe88]
    to be empty=true