AssertContains on strings in jUnit
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;
Use hamcrest Matcher containsString()
// Hamcrest assertionassertThat(person.getName(), containsString("myName"));// Error Messagejava.lang.AssertionError:Expected: a string containing "myName" got: "some other name"
You can optional add an even more detail error message.
// Hamcrest assertion with custom error messageassertThat("my error message", person.getName(), containsString("myName"));// Error Messagejava.lang.AssertionError: my error messageExpected: a string containing "myName" got: "some other name"
Posted my answer to a duplicate question here