Search code examples
javaunit-testingjunitassertj

Asserting individual Objects in List using AssertJ


I am using AssertJ library to perform assertions in my test. In this case I want to test if every Date object in list is after other date.

So I can obviously do the following:

Date dateOne = new Date(someTimestamp);
Date dateTwo = new Date(otherTimestamp);

Assertions.assertThat(dateOne).isAfter(dateTwo);

No questions about it.

But what if I want to test every element of list to make sure that all of them are after given date.


Date dateOne = new Date(someTimestamp);
Date dateTwo = new Date(otherTimestamp);
Date dateThree = new Date(fooBarTimestamp);

List<Date> dates = Arrays.asList(dateOne, dateTwo);

//and here I want to make sure that all Dates in dates are after dateThree

I managed this by creating custom org.assertj.core.api.Condition and used this syntax:

Assertions.assertThat(dates).is(allAfterDate(dateThree));

but the comparator does look very neat and what most important, my SonarQube is complaining that this signature:

Condition<List<? extends Date>> allAfterDate(final Date dateToCompare) {...}

Is breaking Generic wildcard types should not be used in return parameters rule. I tend to believe in SonarQube if I am not sure that this is a rule that I can break this time. And I am not sure.

I like using SoftAssertions so the walkaround would be to use:

SoftAssertions assertions = new SoftAssertions();

dates.forEach( date -> {
    assertions.assertThat(date).isAfter(dateThree);
});

assertions.assertAll();

But I just cannot feel that this should be possible to use this cool AssertJ syntax that most devs like that much ;-)

Is there a way that I can do something similar to this?

Assertions.assertThat(dates).everySingleElement().isAfter(dateThree);

And if this is not possible what would be the best and cleanest way to do this?

(And I know I can supress sonar with //NOSONAR, I just don't want to)



Solution

  • Try allSatisfy:

    assertThat(dates).allSatisfy(date -> assertThat(date).isAfter(dateThree));
    

    hope it helps and is a cool enough syntax for you ;-)