THM
THM

Reputation: 671

How to check if some List contains only one particular element OR is empty using AssertJ

I have:

@Test
public void testSomethingInFooFunction() {
    //given
    Something parameter = new Something();
    //when
    List<Object> result = foo(parameter);
    //then

    // not working
    assertThat(result).isEmpty().or().containsOnly(something());
    assertThat(result).is(v -> v.isEmpty() || v.containsOnly(something());

    //is working
    assertThat(result.isEmpty() || (
        result.contains(something())
        && result.size() == 1)
    ).isTrue();

}

Is there any other way to test condition like:

result.isEmpty() || ( result.contains(something()) && result.size() == 1)

Q: How to simplify it with AssertJ 3.11.1 ?

Upvotes: 1

Views: 4056

Answers (2)

Joel Costigliola
Joel Costigliola

Reputation: 7076

What you are looking for is coming in the next release: https://github.com/joel-costigliola/assertj-core/issues/1304.

assertThat("foo").satisfiesAnyOf(actual -> assertThat(actual).contains("foo"),
                                 actual -> assertThat(actual).isEmpty());

In the meantime, the best option is using anyOf as suggested by Ondra K or yours.

Upvotes: 2

Ondra K.
Ondra K.

Reputation: 3077

This test should fulfill to your needs:

@Test
public void test() {
    List<Integer> integers = Collections.singletonList(1);
    assertThat(integers)
            .has(Assertions.anyOf(
                    new Condition<>(List::isEmpty, "List is empty"),
                    new Condition<>(list -> list.size() == 1 && list.contains(1), "List contains only number 1")
            ));
}

EDIT: You can also you allOf instead of the second condition:

AllOf.allOf(
      new Condition<>(list -> list.size() == 1, "List has size 1"),
      new Condition<>(list -> list.contains(1), "List contains number 1")
)

EDIT 2: Or compare it with the desired list:

new Condition<>(list -> Collections.singletonList(1).equals(list), "the list is equal to a list of the number 1")

Upvotes: 6

Related Questions