Artur
Artur

Reputation: 791

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?

Upvotes: 0

Views: 596

Answers (1)

Stefano Cordio
Stefano Cordio

Reputation: 2257

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)

Upvotes: 1

Related Questions