Home > OS >  AssertJ dynamically check if Optinal is empty or present
AssertJ dynamically check if Optinal is empty or present

Time:11-24

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
@ValueSource(/* 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?)

CodePudding user response:

You can use boolean assert instead

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

CodePudding user response:

From Optional docs:

isPresent: If a value is present, returns true, otherwise false.

So you can simply test like this:

@ParameterizedTest
@ValueSource(/* values */)
void test_presence(Optional<String> opt, boolean present) {
    assertThat(opt.isPresent()).isEqualTo(present);
}
  • Related