Is there a nicer way to write in jUnit
String x = "foo bar";
Assert.assertTrue(x.contains("foo"));
Is there a nicer way to write in jUnit
String x = "foo bar";
Assert.assertTrue(x.contains("foo"));
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.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
use fest assert 2.0 whenever possible EDIT: assertj may have more assertions (a fork)
assertThat(x).contains("foo");
Use hamcrest Matcher containsString()
// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));
// Error Message
java.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 message
assertThat("my error message", person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
got: "some other name"
Posted my answer to a duplicate question here
Use the new assertThat
syntax together with Hamcrest.
It is available starting with JUnit 4.4.
Another variant is
Assert.assertThat(actual, new Matches(expectedRegex));
Moreover in org.mockito.internal.matchers
there are some other interesting matchers, like StartWith
, Contains
etc.
I've tried out many answers on this page, none really worked:
So I stopped trying to make nicely readable code, but used the simple and workable approach mentioned in the question instead.