AssertContains on strings in jUnit

ripper234 picture ripper234 · Jul 7, 2009 · Viewed 184.8k times · Source

Is there a nicer way to write in jUnit

String x = "foo bar";
Assert.assertTrue(x.contains("foo"));

Answer

Yishai picture Yishai · Jul 7, 2009

If you add in Hamcrest and JUnit4, you could do:

String x = "foo bar";
Assert.assertThat(x, CoreMatchers.containsString("foo"));

With some static imports, it looks a lot better:

assertThat(x, containsString("foo"));

The static imports needed would be:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;