0

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?

Stefano Cordio
  • 1,687
  • 10
  • 20
fzt
  • 3
  • 3

1 Answers1

1

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));
Stefano Cordio
  • 1,687
  • 10
  • 20
  • assertThat(Arrays.asList("abc.efg")).containsAnyOf("abc", "d"); it's failed...don't understand,please help! – fzt Aug 04 '21 at 09:41
  • assertThat(actual.contains(oneString)||actual.contains(anotherString)).isTrue(); i tink this will work for me ,but when it failed ,i can't see the string detail when it throw Exception – fzt Aug 04 '21 at 10:00
  • Probably I misunderstood your example. How is `actual` declared? – Stefano Cordio Aug 04 '21 at 12:29
  • just String, like "i am string" ,assertThat(Arrays.asList("i am string")).containsAnyOf("am", "somestring"); – fzt Aug 04 '21 at 12:50
  • Got it, then my answer is wrong because you are looking for string assertions and not collection assertions. I will update it. – Stefano Cordio Aug 04 '21 at 13:12
  • I updated my answer and I raised https://github.com/assertj/assertj-core/issues/2303 for a possible improvement. – Stefano Cordio Aug 05 '21 at 07:26
  • Thank you very much bro, what you did is really admirable – fzt Aug 05 '21 at 08:54
  • No problem, and feel free to accept my answer if that helped :-) – Stefano Cordio Aug 05 '21 at 12:54