Search code examples
javaassertassertionassertj

How to check if at least one string is contained in another with AssertJ?


I would like to check if at least one string is contained in another using AssertJ.

For example, having:

String actual = "I am a string";
String oneString = "am";
String anotherString = "some string";

Currently I can write:

assertThat(actual.contains(oneString) || actual.contains(anotherString)).isTrue();

so if one of the two conditions is true, the assertion will pass. However, in case of failures, there is no detail on what failed exactly.

What would be a good way to achieve this check and have specific details when failed?


Solution

  • Since AssertJ 3.21.0, containsAnyOf is available:

    String actual = "I am a string";
    String oneString = "am";
    String anotherString = "some string";
    
    assertThat(actual).containsAnyOf(oneString, anotherString);
    

    Since AssertJ 3.12.0, satisfiesAnyOf can be used to check if at least one string is contained in actual:

    String actual = "I am a string";
    String oneString = "am";
    String anotherString = "some string";
    
    assertThat(actual).satisfiesAnyOf(s -> assertThat(s).contains(oneString),
                                      s -> assertThat(s).contains(anotherString));