Assert same condition on all elements of a collection
Asked Answered
F

1

15

I'm working with AssertJ and I need to check that all objects in a list have intField > 0. Something like this:

assertThat(myObjectList).extracting(p -> p.getIntField()).isGreaterThan(0);

What's the correct way to achieve this? Should I use some other library?

Finding answered 28/11, 2018 at 18:48 Comment(0)
O
30

Option 1:

Use allMatch(Predicate):

assertThat(asList(0, 1, 2, 3))
    .allMatch(i -> i > 0);
java.lang.AssertionError: 
Expecting all elements of:
  [0, 1, 2, 3]
to match given predicate but this element did not:
  0

Option 2 (as suggested by Jens Schauder):

Use Consumer<E>-based assertions with allSatisfy:

assertThat(asList(0, 1, 2, 3))
        .allSatisfy(i ->
                assertThat(i).isGreaterThan(0));

The second option may result in more informative failure messages.

In this particular case the message highlights that some elements are expected to be greater than 0

java.lang.AssertionError: 
Expecting all elements of:
  [0, 1, 2, 3]
to satisfy given requirements, but these elements did not:

0
error: 
Expecting actual:
  0
to be greater than:
  0
Overleap answered 28/11, 2018 at 19:20 Comment(4)
I didn't know allMatch method. That's exacly what I was looking for. Thank you very much!Finding
One may also use allSatisfy which allows to write a consumer containing assertions. This is a little more code but also more flexible and potentially results in better failure messages.Xochitlxp
@JensSchauder thank you, added it as the second option to the answerOverleap
Incidentally, per the allMatch Javadocs, it looks like these are and have can be used to the same effect: assertThat(asList(0, 1, 2, 3)).are(new Condition<>(i -> i > 0, "greater than 0")) & assertThat(asList(0, 1, 2, 3)).have(new Condition<>(i -> i > 0, "a value greater than 0")).Marcasite

© 2022 - 2024 — McMap. All rights reserved.