2

Example:

public class Office {
  List<Employee> employee;
}

How do I assert that in my List<Office> offices there are none with no employees? Is it possible to assert this with one assertion chain?

George
  • 2,820
  • 4
  • 29
  • 56

2 Answers2

9

If I understand your question correctly you want to check that all offices have employee, if so allSatisfy can be used like:

assertThat(offices).allSatisfy(office -> {
                              assertThat(office.employee).isNotEmpty();
                            });

There is also a noneSatisfy assertion available BTW.

Joel Costigliola
  • 6,308
  • 27
  • 35
  • Before you replied, I went with `.doesNotHave(new Condition<>(CollectionUtils::isEmpty, "Empty Employees")`. Is there any reason there's no method that takes in a Predicate? Something like: `.allSatisfy(CollectionUtils::isNotEmpty)` Thanks. – George Apr 01 '19 at 20:47
  • there is one: `allMatch` – Joel Costigliola Apr 02 '20 at 20:47
1

You could solve this via allSatisfy iterable assertion like shown in the following example:

    @Test
    public void assertInnerPropertyInList() {
        List<Office> officesWithEmptyOne = List.of(
                new Office(List.of(new Employee(), new Employee())),
                new Office(List.of(new Employee())),
                new Office(List.of()));

        List<Office> offices = List.of(
                new Office(List.of(new Employee(), new Employee())),
                new Office(List.of(new Employee())));

        // passes
        assertThat(offices).allSatisfy(office -> assertThat(office.getEmployee()).isNotEmpty());

        // fails
        assertThat(officesWithEmptyOne).allSatisfy(office -> assertThat(office.getEmployee()).isNotEmpty());
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Office {
        private List<Employee> employee;
    }

    @Data
    @AllArgsConstructor
    public class Employee {
    }

And you can see that the second assertion fails with the message:

java.lang.AssertionError: 
Expecting all elements of:
  <[AssertJFeatureTest.Office(employee=[AssertJFeatureTest.Employee(), AssertJFeatureTest.Employee()]),
    AssertJFeatureTest.Office(employee=[AssertJFeatureTest.Employee()]),
    AssertJFeatureTest.Office(employee=[])]>
to satisfy given requirements, but these elements did not:

  <AssertJFeatureTest.Office(employee=[])> 
Expecting actual not to be empty

Annotations are coming from Lombok.

mle
  • 2,466
  • 1
  • 19
  • 25