JUnit: Is there a way to assert all array values at once?

I have a map in which its values are a simple pojo. For example (in a very loosely code):

Class Data{
  int a;
  Boolean b;
}

Map<Integer, Data> myMap = new HashMap<>();

Now the map is being populated with values. And at then end I would like to assert that all the b values of the data object of all map entries are, for example, true.

So I tried something like that:

private void computeAllBooleans(){

    allBooleansStatus = true;
    myMap.values()
        .forEach(data ->
            allBooleansStatus = allBooleansStatus && data.getB();
}
  1. Is there a more concise way to achieve that?
  2. Is there a way to assert it with JUnit (or other relevant frameworks like hamcrest, assertj, etc.) assertions?

(I noticed this link but didn't understand how can I use the suggested answers there...)


Solution 1:

you can use more elegant way with the assertj library using allMatch or allSatisfy:

https://assertj.github.io/doc/#assertj-core-group-satisfy

List<TolkienCharacter> hobbits = list(frodo, sam, pippin);

// all elements must satisfy the given assertions
assertThat(hobbits).allSatisfy(character -> {
  assertThat(character.getRace()).isEqualTo(HOBBIT);
  assertThat(character.getName()).isNotEqualTo("Sauron");
});

Solution 2:

With AssertJ Core you can chain extracting and containsOnly:

Map<Integer, Data> myMap = new HashMap<>();
myMap.put(1, new Data(1, true));
myMap.put(2, new Data(2, true));
myMap.put(3, new Data(3, true));

assertThat(myMap.values()).extracting(Data::getB).containsOnly(true);

The benefit of using AssertJ is also a nicely formatted error message in case of failures. For example, the following:

Map<Integer, Data> myMap = new HashMap<>();
myMap.put(1, new Data(1, true));
myMap.put(2, new Data(2, false));
myMap.put(3, new Data(3, false));

assertThat(myMap.values()).extracting(Data::getB).containsOnly(true);

would fail with:

java.lang.AssertionError: 
Expecting ArrayList:
  [true, false, false]
to contain only:
  [true]
but the following element(s) were unexpected:
  [false, false]

More Iterable assertions are described in the official documentation.