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.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
Using String.contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.
The first and foremost way to check for the presence of a substring is the . contains() method. It's provided by the String class itself and is very efficient. Note: The .
Contains() is a string method. This method is used to check whether the substring occurs within a given string or not. It returns the boolean value. If substring exists in string or value is the empty string (“”), then it returns True, otherwise returns False.
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))));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With