How to check String in response body with mockMvc
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
MockMvc lets you test Spring MVC endpoints without starting a real server. One of the most common assertions is checking whether the response body equals a string or contains a particular fragment.
The exact matcher depends on what you want to prove. For plain text responses, content().string(...) is usually enough. For JSON responses, checking one fragment can work, but structure-aware assertions are often better.
Exact Match Versus Partial Match
If the whole response body should match exactly, use content().string("..."). If you only care that the body contains some text, combine it with a Hamcrest matcher such as containsString.
Here is a minimal controller and test:
The first test is flexible. The second is strict and will fail if whitespace, punctuation, or formatting changes.
Reading the Body as Text
If you need more control than a matcher provides, you can inspect the response manually:
This is useful when the assertion is too custom for a single built-in matcher. You can normalize whitespace, split lines, or run several assertions against the same body.
Plain Text Versus JSON
Checking raw text is fine for plain text endpoints, HTML fragments, or simple error messages. For JSON, substring checks can be brittle because formatting changes may break the test even when the JSON content is still correct.
For JSON responses, prefer jsonPath when possible:
That assertion is more precise than checking whether the body merely contains "Alice".
When a Substring Assertion Is the Right Tool
There are still many cases where containsString is exactly what you want. Server-rendered HTML pages, plain-text health endpoints, and error messages often contain extra markup or context that would make an exact-string assertion too fragile.
For example, if an HTML response includes a heading, a timestamp, and a footer, asserting the full body would couple the test to layout details. Checking that the key phrase is present is often the better balance between accuracy and maintainability.
The same idea applies to validation errors. If the response says "email is required" inside a larger payload, the test should usually assert that the message appears, not that the entire response body matches one exact line.
Common Pitfalls
- Using exact-string assertions for responses that contain dynamic data such as timestamps or generated IDs.
- Checking raw JSON text with
containsStringwhen ajsonPathassertion would be more stable. - Forgetting character encoding when the response contains non-ASCII text and you read it manually.
- Asserting only the body and ignoring the status code or content type, which can hide real failures.
Summary
- Use
content().string("...")when the entire response must match exactly. - Use
content().string(containsString("..."))when only part of the body matters. - Read the body with
getContentAsString()if you need custom assertions. - Prefer
jsonPathfor JSON payloads instead of substring checks. - Combine body assertions with status and content-type checks for stronger tests.
Related reading
- how to check the jdk version used to compile a .class file
- How to check two condition while using ConditionalOnProperty or ConditionalOnExpression
- How to check type of variable in Java?
- How to check whether a given string is valid JSON in Java
- How to correctly write async XUnit test?
- How to Create a Kafka Consumer Record from a String to build Junit test case
- How to clear gradle cache?
- How to clear the console using Java?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.