Search code examples
javaassertj

Does AssertJ provide an assertion method on iterables that has a Consumer as argument?


AssertJ provides the method hasValueSatisfying(Consumer<T> requirement) for Java Optional objects. This method allows to create assertions on the optional value like this:

    assertThat(myOptional).hasValueSatisfying(v -> {
        assertThat(v.getFirstName()).isEqualTo("Stephen");
        assertThat(v.getLastName()).isEqualTo("Smith");
        assertThat(v.getAge()).isEqualTo(22);
    });

Is there any equivalent method for collections? Of cause I can misuse the method allMatch(Predicate<? super T> predicate) like this

    assertThat(myIcelanderFriends).extracting(Person::getAddress)
                    .allMatch(a -> {
                        assertThat(a.getCountry()).isEqualTo("Iceland");
                        assertThat(a.getPhoneContryCode()).isEqualTo("+354");
                        assertThat(a.getSurname()).endsWith("son");
                        return true; // Predictes must return a boolean
                    });

but then I have to add the misleading return true; line as a Predicate needs a return value. I'd prefer to have here also haveValuesSatisfying(Consumer<T> requirement) method. Did I oversee such a method or does it not exist (yet)?


Solution

  • Nope there is no such method yet ... but will be in 3.6.0 : https://github.com/joel-costigliola/assertj-core/issues/711