Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analog of everyItem() from Hamcrest in AssertJ

Is there analog of everyItem() from Hamcrest in AssertJ?

I have a list of emails and need to do Assertion to check that each email contains substring "alex". Currently the only way I can do it with AssertJ is as follows:

    List<String> actual = Arrays.asList("[email protected]", "[email protected]", "[email protected]", "[email protected]");

    SoftAssertions softly = new SoftAssertions();
    for(String email: actual ) {
        softly.assertThat(email).contains("alex");
    }

    softly.assertAll();

Can be done without Soft Assertions there as well, but I'd prefer to check all the item of the list.

Is there any more compact way to do so? To be specific, is there a way in AssertJ to check each item of the list to match a substring?

In Hamcrest I can do it in one line:

assertThat(actual, everyItem(containsString("alex")));

But in AssertJ looks like in any way I have to manually iterate through the list.

like image 324
Alex F Avatar asked Jan 26 '26 17:01

Alex F


1 Answers

Assertj 3.6.0 introduced the allSatisfy assertion, which allows you to perform scoped assertions on each element of the iterable.

Therefore you could do what you want with

assertThat(actual).allSatisfy(elem -> assertThat(elem).contains("alex"));
like image 116
Dan Avatar answered Jan 28 '26 06:01

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!