[java] AssertContains on strings in jUnit

Is there a nicer way to write in jUnit

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

This question is related to java string junit assert

The answer is


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:

  • org.hamcrest.CoreMatchers.containsString does not compile, cannot resolve method.
  • JUnitMatchers.containsString is depricated (and refers to CoreMatchers.containsString).
  • org.hamcrest.Matchers.containsString: NoSuchMethodError

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

Use the new assertThat syntax together with Hamcrest.

It is available starting with JUnit 4.4.


assertj variant

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to junit

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to resolve Unneccessary Stubbing exception JUnit 5: How to assert an exception is thrown? How do I mock a REST template exchange? Class Not Found: Empty Test Suite in IntelliJ Unable to find a @SpringBootConfiguration when doing a JpaTest Failed to load ApplicationContext (with annotation) Example of Mockito's argumentCaptor Mockito - NullpointerException when stubbing Method Spring jUnit Testing properties file

Examples related to assert

What is “assert” in JavaScript? How to handle AssertionError in Python and find out which line or statement it occurred on? How can I check if some text exist or not in the page using Selenium? PHPUnit assert that an exception was thrown? What is the use of "assert"? How do I check (at runtime) if one class is a subclass of another? Java/ JUnit - AssertTrue vs AssertFalse What does the "assert" keyword do? Proper way to assert type of variable in Python How to check if an object is a list or tuple (but not string)?