3

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("alex@gmail.com", "alex1@gmail.com", "ale2@hotmail.com", "bred@gmail.com");

    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.

Alex F
  • 273
  • 4
  • 13

5 Answers5

3

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"));
Dan
  • 3,490
  • 2
  • 22
  • 27
2

I found 2 solutions: 1) use java 8

actual.forEach( val -> softly.assertThat(val).contains("alex"));

2) make an utility class

public class AssertUtils {
    public static Condition<String> ContainsCondition(String val) {
        return new Condition<String>() {
            @Override
            public boolean matches(String value) {
                return value.contains(val);
            }
        };
    }
}

and use it:

softly.assertThat(actual).are(AssertUtils.ContainsCondition("alex"));
Vovka
  • 599
  • 3
  • 10
2

You can build AssertJ condition with predicate and use are/have assertion:

 @Test
 public void condition_built_with_predicate_example() {
     Condition<String> fairyTale = new Condition<String>(s -> s.startsWith("Once upon a time"), "a %s tale", "fairy");
     String littleRedCap = "Once upon a time there was a dear little girl ...";
     String cindirella = "Once upon a time there was a ...";
     assertThat(asList(littleRedCap, cindirella)).are(fairyTale);

}

Edit: As pointed by Dan I would now use allSatisfy.

Joel Costigliola
  • 6,308
  • 27
  • 35
1

I prefer to use this form of allMatch as follow:

assertThat(movies).extracting("title").allMatch(s -> s.toString().contains("the"));

Elie Nehmé
  • 229
  • 2
  • 5
0

I just rely on Java 8 stream functionality for that kind of stuff:

assertThat(actual.stream().allMatch(s -> s.contains("alex"))).isTrue();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Thanks, I see your point, but it's going to produce obscure message on failure like "Expecting [true] but was [false] – Alex F Sep 30 '15 at 18:14