jUnit
AssertContains
testing
Java
unit testing

JUnit assert contains for strings

Codemia Knowledge Hub ·

JUnit has no built-in assertContains for strings. Assert that actual.contains(expected) is true, or use a richer assertion library such as AssertJ or Hamcrest for more expressive failure messages.

assertTrue with String.contains

The simplest JUnit-only version:

java
1import static org.junit.jupiter.api.Assertions.assertTrue;
2
3import org.junit.jupiter.api.Test;
4
5class MessageTest {
6    @Test
7    void responseContainsId() {
8        String response = "Created order with id=42";
9
10        assertTrue(response.contains("id=42"));
11    }
12}

This is valid, keeps the dependency list small and works for many tests. Its weakness is the failure output, which is less descriptive than a purpose-built string assertion.

Adding a failure message

When the substring check is central to the test, include a message that shows what was expected:

java
1import static org.junit.jupiter.api.Assertions.assertTrue;
2
3import org.junit.jupiter.api.Test;
4
5class MessageTest {
6    @Test
7    void responseContainsId() {
8        String response = "Created order with id=42";
9
10        assertTrue(
11            response.contains("id=42"),
12            () -> "Expected substring id=42 in response: " + response
13        );
14    }
15}

The supplier form builds the message lazily and makes failures much easier to diagnose.

Checking for null separately

If the string could be null, assert that first so the failure tells you what actually went wrong:

java
1import static org.junit.jupiter.api.Assertions.assertNotNull;
2import static org.junit.jupiter.api.Assertions.assertTrue;
3
4import org.junit.jupiter.api.Test;
5
6class MessageTest {
7    @Test
8    void responseContainsToken() {
9        String response = getResponse();
10
11        assertNotNull(response, "response should not be null");
12        assertTrue(response.contains("token"));
13    }
14
15    private String getResponse() {
16        return "token=abc123";
17    }
18}

This is clearer than writing response != null && response.contains("token") inside one assertion.

AssertJ for readable assertions

If your project already uses AssertJ or Hamcrest, containment checks read better. With AssertJ:

java
1import static org.assertj.core.api.Assertions.assertThat;
2
3import org.junit.jupiter.api.Test;
4
5class MessageTest {
6    @Test
7    void responseContainsId() {
8        String response = "Created order with id=42";
9
10        assertThat(response).contains("id=42");
11    }
12}

This reads closer to English and usually produces better failure messages. JUnit is still the test runner; AssertJ only provides the assertions.

Ignoring case

String.contains is case-sensitive. If that is not what you want, normalize both sides or use an assertion library feature that says so explicitly:

java
1import static org.junit.jupiter.api.Assertions.assertTrue;
2
3import java.util.Locale;
4import org.junit.jupiter.api.Test;
5
6class MessageTest {
7    @Test
8    void responseContainsSubstringIgnoringCase() {
9        String response = "Order Status: Completed";
10        String expected = "status: completed";
11
12        assertTrue(
13            response.toLowerCase(Locale.ROOT).contains(expected.toLowerCase(Locale.ROOT))
14        );
15    }
16}

Using Locale.ROOT avoids locale-dependent casing surprises.

When containment is the wrong check

Sometimes a substring assertion stands in for what you really want:

  • equality
  • a prefix or suffix check
  • a regex or pattern match
  • structured data validation such as JSON parsing

For example, if the response is JSON, checking contains("\"status\":\"ok\"") is usually weaker than parsing the JSON and asserting the actual field value.

Use containment when the test is genuinely about substring presence, not because it is the fastest thing to type.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms