Search code examples
assertj

Test that either one property contains value in AssertJ


Having following code:

@Data
@AllArgsConstructor
public class TolkienCharacter{
    String nick;
    String name;
    String surname;
}


@Test
void go(){
    TolkienCharacter frodo = new TolkienCharacter("GoodFrodo", "Frodo", "Baggins");
    TolkienCharacter togo = new TolkienCharacter("Hobbit", "Togo", "Goodbody");
    List<TolkienCharacter> goodCharacters = Arrays.asList(frodo, togo);

I need to write assert, that checks that all elements in the goodCharacters list have nick or surname, which contains "good".

What is the best way to do it?


Solution

  • A solution could be:

    assertThat(goodCharacters).extracting(TolkienCharacter::getNick, TolkienCharacter::getSurname)
        .allSatisfy(tuple -> assertThat(tuple.toList()).asInstanceOf(list(String.class))
            .anySatisfy(string -> assertThat(string).containsIgnoringCase("good")));
    

    In case of failures, the error message would be like the following:

    java.lang.AssertionError: 
    Expecting all elements of:
      [("GoodFrodo", "Baggins"), ("Hobbit", "Badbody")]
    to satisfy given requirements, but these elements did not:
    
    ("Hobbit", "Badbody")
    error: 
    Expecting any element of:
      ["Hobbit", "Badbody"]
    to satisfy the given assertions requirements but none did:
    
    "Hobbit"
    error: 
    Expecting actual:
      "Hobbit"
    to contain:
      "good"
     (ignoring case)
    
    "Badbody"
    error: 
    Expecting actual:
      "Badbody"
    to contain:
      "good"
     (ignoring case)