At the moment there isn't any matcher in hamcrest with this requeriment, despite you can combine multiple this is not possible yet.
So, in cases like yours the best solution in my opinion is to create your own matcher Why?
- It can be reused
- Is maintainable
- Is more readable
So in your case you need to match the first list contains any string of the second one, you can create a Matcher like next:
public class ContainsStringsOf extends BaseMatcher<List<String>> {
private final List<String> valuesToCompare;
public ContainsStringsOf(List<String> valuesToCompare) {
this.valuesToCompare = valuesToCompare;
}
@Override
public void describeTo(Description description) {
description.appendText("doesn't contains all of " + valuesToCompare.toString() + " text");
}
@Override
public boolean matches(Object o) {
List<String> values = (List<String>) o;
for (String valueToCompare : valuesToCompare) {
boolean containsText = false;
for (String value : values) {
if (value.contains(valueToCompare)) {
containsText = true;
}
}
if (!containsText) {
return false;
}
}
return true;
//note: you can replace this impl with java-8 @florian answer comparison
//return valuesToCompare.stream().allMatch(exp -> strings.stream().anyMatch(st-> st.contains(exp)))
}
@Factory
public static Matcher<List<String>> containsStringsOf(List<String> collection) {
return new ContainsStringsOf(collection);
}
}
Then you can use it is just as hamcrest matcher is used:
List<String> expectedStrings = Arrays.asList("link1", "link2");
List<String> strings = Arrays.asList("lalala link1 lalalla", "lalalal link2 lalalla");
Assert.assertThat(strings , containsStringsOf(expectedStrings));