Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert same condition on all elements of a collection

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?

like image 696
davioooh Avatar asked Dec 24 '22 02:12

davioooh


1 Answers

Option 1:

Use allMatch(Predicate):

assertThat(asList(0, 2, 3))
    .allMatch(i -> i > 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> 
Expecting:
 <0>
to be greater than:
 <0> 
like image 124
Denis Zavedeev Avatar answered Jan 06 '23 02:01

Denis Zavedeev