How to check String in response body with mockMvc
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.
If you are the bearer of bad news and expecting a 400 Bad Request, drop status().isBadRequest()
in your test:
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:
When you want to find Waldo in a text crowd, lean on containsString()
:
Interacting with JSON responses
Put json()
or jsonPath()
at your service to compare either the complete JSON blueprint or individual components:
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):
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:
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).
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.
Was this article helpful?