Search code examples
javahamcrest

Assert that one of string in array contains substring


List<String> expectedStrings = Arrays.asList("link1", "link2");
List<String> strings = Arrays.asList("lalala link1 lalalla", "lalalal link2 lalalla");

For each expectedString, I need assert that any of string in the 'strings' contains expectedString. How I may assert this with Hamcrest? Thanks for your attention.


Solution

  • Update

    After checking this old answer, I found that you can use a better combination of built-in matchers making both the assertion and the error messages more readable:

    expectedStrings.forEach(expectedString -> 
        assertThat(strings, hasItem(containsString(expectedString))));
    

    Original answer for reference

    You can do it quite easily with streams:

    assertThat(expectedStrings.stream().allMatch(
        expectedString -> strings.stream()
                                 .anyMatch(string -> string.contains(expectedString))),
        is(true));
    

    allMatch will make sure all of the expectedStrings will be checked, and with using anyMatch on strings you can efficiently check if any of the strings contains the expected string.