AssertContains on strings in jUnit

Viewed 254915

Is there a nicer way to write in jUnit

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

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 the new assertThat syntax together with Hamcrest.

It is available starting with JUnit 4.4.

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"));

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");
 }

}

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

assertj variant

import org.assertj.core.api.Assertions;
Assertions.assertThat(actualStr).contains(subStr);

The previous answers are fairly good if you are able and willing to add external libraries. For various reasons, this might not be the case. If you can't/don't want to add another dependency to your project, or if you just want to keep hamcrest at arms length, you could use the parts of hamcrest that come with JUnit.

For example, org.hamcrest.BaseMatcher and org.hamcrest.Matcher come with JUnit 4.10. One implementation could be:

public class StringMatchers {
    public static Matcher<String> contains(String expected) {
        return new BaseMatcher<String>() {
            @Override
            public boolean matches(Object actual) {
                String act = (String) actual;
                
                return act.contains(expected);
            }

            @Override
            public void describeTo(Description desc) {
                desc.appendText("should contain ").appendValue(expected);
            }
        };
    }
}

and then you can import it into other test files with import static <package>.StringMatchers.contains. This will leave you with the statement:

assertThat(x, contains(y));

PS. This is suspiciously similar to other libraries, so I would be surprised if they were implemented much different.

src: https://programmingideaswithjake.wordpress.com/2014/11/08/advanced-creation-of-hamcrest-matchers/ **not everything in here works!

Related