Explain Codes LogoExplain Codes Logo

How to check String in response body with mockMvc

java
mockmvc
testing
spring-mvc
Anton ShumikhinbyAnton Shumikhin·Jan 18, 2025
TLDR

Put MockMvcResultMatchers.content() to work. Pair it with containsString() for plain text checks, or json() for JSON verifications in your andExpect() after running perform() on mockMvc. Assert the expected substring or JSON snippet directly.

// Hunting for the "substring deer" in the "text forest" mockMvc.perform(get("/myLittleEndpoint")) .andExpect(status().isOk()) .andExpect(content().string(containsString("deerInTheHeadlights"))); // Catching the "JSON fish" in the "endpoint sea" mockMvc.perform(get("/myOceanEndpoint")) .andExpect(status().isOk()) .andExpect(content().json("{\"fish\":\"inTheNet\"}"));

If you are the bearer of bad news and expecting a 400 Bad Request, drop status().isBadRequest() in your test:

// Knock, knock. Who's there? 400 Bad Request. 400 Bad Request, who? mockMvc.perform(post("/rudeEndpoint")) .andExpect(status().isBadRequest());

Diving into the deep end with string checks

The speedy route will get you there, but knowing the inner workings behind verifying response strings can level up your testing might.

Matching the big picture versus the smaller fragment

To compare the whole shebang, the string() matcher leaps into action:

// The perfectionist that wants everything to match andExpect(content().string("mirrorMirrorOnTheWall"));

When you want to find Waldo in a text crowd, lean on containsString():

// The code detective that sifts through the clues andExpect(content().string(containsString("wheresWaldo")));

Interacting with JSON responses

Put json() or jsonPath() at your service to compare either the complete JSON blueprint or individual components:

// The architect who sees the grand design andExpect(content().json("{\"critical\":\"detail\"}")); // The engineer who cares about the nuts and bolts andExpect(jsonPath("$.key", is(expectedValue)));

Championship string checking techniques

Throw 💡 on your testing pathways with these pro tips. Ask yourself, would Sherlock Holmes write lazy tests? I think not!

Assert your ground

An AssertionError is your Watson, the trustworthy sidekick pointing you to the oddities. AssertionError is a chatterbox, offering valuable tidbits on where things went sideways.

JSON caveats

When toiling with JSON responses, remember form follows function. Using jsonPath() correctly is a straitjacket – it keeps your test's crazy expectations of type and value in check.

Venture beyond string equality

If responses carry dynamic strings or mask information, unsheath your regular expressions or custom matchers. They are your secret weapons.

Betting on mockMvc advantages

MockMvc is not just a testing tool; it's your Swiss knife for inspecting Spring MVC controllers. Here's how to exploit it fully:

Content diplomacy

When dealing with APIs that sip on content negotiation, set the ContentType (the potluck invitation):

// Serving JSON snacks at the "/treats" party mockMvc.perform(post("/treats") .contentType(MediaType.APPLICATION_JSON) .content(jsonBites));

Mock data march

When your test mocks an encyclopedic JSON or one from a real-world assembly line, redirect the script to an external file:

// The test director shouting, "Cue mock data!" String jsonScript = new String(Files.readAllBytes(Paths.get("path/to/siliconValley"))); andExpect(content().json(jsonScript));

Meeting your testing coverage goals

What good is a toolbox if you only use a hammer? Exploit the full potential of your tools for more robust and varied tests.

Dynamic JsonPath

A JsonPath is a chameleon; it adapts to match complex JSON layouts and extracts values like a champ. It can match anything from a hippo to binary data (don't try that at home).

// Playing matchmaker with pattern andExpect(jsonPath("$.date", matchesPattern("^[0-9]{4}-[0-9]{2}-[0-9]{2}$"))); // Sizing up the array contenders andExpect(jsonPath("$.items", hasSize(greaterThan(2))));

Handling Spring versions

Earlier than Spring 4.1, leave JSON processing to Jackson. Later versions have built-in support, making it, as Thor says, a piece of cake!

When murphy's law strikes

Be on guard for sneaky encoding issues and content type mismatches; the covert ops of the testing world. Ensure the accept header and content type handshake correctly.