Want a JUnitMatchers AssertThat to test string contains 3 or more sub strings (currently using assertThat ... both ... and ....)
Asked Answered
L

3

13
import static org.junit.matchers.JUnitMatchers.both;
import static org.junit.matchers.JUnitMatchers.containsString;

Now I check it contains foo and bar as below ...

        Assert.assertThat(text,
            both(containsString("foo")).
            and(containsString("bar")));

What is cleanest way to test that it contains 3 or more strings e.g. 'foo', 'bar' and 'baz' ?

Leisure answered 1/7, 2013 at 11:52 Comment(0)
E
30

Use AllOf

 Assert.assertThat(test, CoreMatchers.allOf(
      containsString("foo"),
      containsString("bar"),
      containsString("bar2"),
      containsString("ba3")));
Entablement answered 1/7, 2013 at 11:55 Comment(0)
R
3

I don't know a elegant way in pure JUnit but you could take a look at Fixtures for Easy Software Testing

I'm using it for quite some time and it makes like so much easier.

assertThat(text).contains("foo").contains("bar");
Roee answered 1/7, 2013 at 11:56 Comment(1)
+1 FEST/AssertJ. You could use assertThat(text).contains("foo", "bar", "baz"); - it's even more succinct.Pacificism
L
1

Here's a static method that provides some syntactic sugar for this:

public static org.hamcrest.Matcher<String> containsAll(String... substrings) {
    List<Matcher<? super String>> matchers =
            Arrays.stream(substrings)
                    .map(s -> CoreMatchers.containsStringIgnoringCase(s))
                    .collect(Collectors.toList());
    return CoreMatchers.allOf(matchers);
}

Usage:

assertThat(someValue, containsAll("foo", "bar"));
Langobard answered 18/10, 2022 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.