It's too late, but just to update I got it done with below syntax
import org.hamcrest.core.StringContains;
import org.junit.Assert;
Assert.assertThat("this contains test", StringContains.containsString("test"));
You can use assertj-fluent assertions. It has lot of capabilities to write assertions in more human readable - user friendly manner.
In your case, it would be
String x = "foo bar";
assertThat(x).contains("foo");
It is not only for the strings, it can be used to assert lists, collections etc.. in a friendlier way
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.
Example (junit version- 4.13)
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TestStr {
@Test
public void testThatStringIsContained(){
String testStr = "hi,i am a test string";
assertThat(testStr).contains("test");
}
}
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
I've tried out many answers on this page, none really worked:
So instead of writing readable code, I decided to use the simple and workable approach mentioned in the question instead.
Hopefully another solution will come up.
use fest assert 2.0 whenever possible EDIT: assertj may have more assertions (a fork)
assertThat(x).contains("foo");
assertj variant
import org.assertj.core.api.Assertions;
Assertions.assertThat(actualStr).contains(subStr);
Source: Stackoverflow.com