Reputation: 3030
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?
Upvotes: 2
Views: 8567
Reputation: 7126
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.
Upvotes: 9
Reputation: 2550
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.
Upvotes: 1