AssertJ 验证带有列表字段的对象列表不为空

AssertJ Verify List of Objects with a List field is not empty

示例:

public class Office {
  List<Employee> employee;
}

我如何断言在我的 List<Office> offices 中有 none 没有员工?是否可以用一个断言链来断言?

您可以通过 allSatisfy iterable assertion 解决此问题,如下例所示:

    @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 {
    }

您可以看到第二个断言失败并显示消息:

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

注释来自 Lombok。

如果我对你的问题理解正确,你想检查是否所有办公室都有员工,如果是这样 allSatisfy 可以像这样使用:

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

顺便说一句,还有一个 noneSatisfy 断言可用。