I’m using AssertJ and need to verify that every object in a list satisfies a certain condition for example, ensuring all objects have intField > 0. My current attempt looks like this:
assertThat(myObjectList).extracting(p -> p.getIntField()).isGreaterThan(0);
However, this doesn’t seem to work as expected. What’s the right way to assert that all elements in a collection meet the same condition? Should I use allSatisfy() or a different AssertJ approach?
AssertJ provides the allSatisfy method to assert a condition on every element individually:
import static org.assertj.core.api.Assertions.assertThat;
assertThat(myObjectList).allSatisfy(obj ->
assertThat(obj.getIntField()).isGreaterThan(0)
);
This runs the lambda for each element, and the assertion fails if any element doesn’t meet the condition. It’s very readable and keeps the logic close to the element.
If you prefer a more functional style, you can extract the field and use allMatch with a predicate:
assertThat(myObjectList)
.extracting(MyObject::getIntField)
.allMatch(value -> (Integer) value > 0);
This way, you assert that all extracted values satisfy your predicate. Remember to cast properly since extracting() can return Object unless you use extractingInt.
For numeric fields, extractingInt is convenient and avoids boxing:
assertThat(myObjectList)
.extractingInt(MyObject::getIntField)
.allMatch(i -> i > 0);
This approach is concise and efficient because it deals directly with primitives and works well for fields like int or long.