Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert that one of string in array contains substring

Tags:

java

hamcrest

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.

like image 883
Hamster Avatar asked Jan 24 '17 12:01

Hamster


People also ask

How do you check if a string is present in an array of strings?

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.

How do you check if a string contains any of some strings?

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.

How do you check if a substring is present in a string array in Java?

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 .

How do you check if a string exists in a string array C#?

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.


1 Answers

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.

like image 63
Florian Link Avatar answered Oct 04 '22 04:10

Florian Link