AssertJ验证具有“列表”字段的对象列表不为空

时间:2019-04-01 15:06:49

标签: assertj

示例:

public class Office {
  List<Employee> employee;
}

我如何断言我的List<Office> offices中没有雇员?可以用一个断言链来断言吗?

2 个答案:

答案 0 :(得分:1)

您可以通过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

注释来自龙目岛。

答案 1 :(得分:1)

如果我正确理解了您的问题,则要检查所有办公室是否都有员工,如果可以,allSatisfy可以这样使用:

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

还有一个noneSatisfy断言可用。