3

What is the best way to assert that each element in a collection of strings contains a particular substring?

Something like

List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");

assertThat(list, eachElementContains("foobar")); // pass
Marteng
  • 1,179
  • 13
  • 31

4 Answers4

5

Something simple like:

list.forEach(string -> {
    assertTrue(string.contains("foobar"));
});

This doesn't use Hamcrest matchers but has the same semantics.

cameron1024
  • 9,083
  • 2
  • 16
  • 36
  • The braces of your lambda are redundant here btw. – Michael Aug 22 '19 at 10:58
  • 1
    Yes, i go through phases of wanting all lambdas to fit on a single line, and other phases of wanting everything spread out, currently in a spread out phase :p – cameron1024 Aug 22 '19 at 10:59
  • This will make an assert for every element from list. I think he want one assert over all. – KunLun Aug 22 '19 at 11:03
  • 1
    Is there a reason why this is preferrable? I am not familiar with the specifics of the assert variants, so am unaware if this leads to performance impacts. If so, you could also use `assertTrue(list.stream().allMatch(s -> s.contains("foobar")));` – cameron1024 Aug 22 '19 at 11:05
  • Yes, @KunLun. If I have 100 elements in a list It would be nice when all elements are checked instead of failing at the first not-match. Furthermore, in the error output, it's hard to see which of the 100 elements made the assertion fail. It does its job, tho. – Marteng Aug 22 '19 at 11:06
3

A simple solution is to use hamcrest library. Please try :

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.everyItem;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class MyTest {

    @Test
    public void test() {
        List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
        assertThat(list, (everyItem(containsString("foobar"))));
    }
}
zpavel
  • 951
  • 5
  • 11
2

If you use AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

you could do the following:

List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
list.forEach(entry->assertThat(entry).describedAs("should contains 'foobar'").contains("foobar"));
htmoia
  • 429
  • 4
  • 9
-1

I think this will do the trick

         List<String> result = list.stream()                // convert list to stream
             .filter(str ->str.indexOf("foobar")!=-1)     // collects all "foobar" substring
             .collect(Collectors.toList());              // collect the output and convert streams to a List

 assertThat(list.equals(result)).isTrue();
yogev levi
  • 369
  • 1
  • 4
  • 21