Search code examples
unit-testingassertionshamcrestassertj

How to assert attribute of contents of a list using Assertj?


Such is the method.

List<User> someMethod() {
    User user[] = new Users[3];
    user[0] = new User();
    user[0].setImage(new Image(Constants.HOME));
    user[1] = new User();
    user[1].setImage(new Image(Constants.NOT_HOME));
    user[2] = new User();
    user[2].setImage(new Image(Constants.HOME));   
    return Arrays.asList(user);
}

How can I test the test the above code. I need to verify that some of the users have images on HOME.

I could try to re-build entire users list and compare it. But, I do not want to do that.

I tried something like this,

assertThat(Optional.of(service.someMethod())).hasValueSatisfying((a)->a.stream().allMatch((b)->b.getImage().getImageUrl().equals(Constants.HOME)));

The assertion is always true in this context, because the hasValueSatisfying is using Consumer<T> as parameter. But, I want to use in in the following way - AssertJ way

Can I use Hamcrest in some way to solve this?


Solution

  • I would use AssertJ extracting feature:

    assertThat(users).extracting(user -> getImage().getImageUrl())
                     .contains(Constants.HOME)
    

    I'm assuming here that users is a List<User> not an optional of List<User>.