How to check String in response body with mockMvc

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to check String in response body with mockMvc

๐Ÿ”Ž How to check String in response body with mockMvc? ๐Ÿ“

So you're working on an integration test using mockMvc and you want to check if a specific string is present in the response body. You've tried a few things but haven't had any success. Don't worry, I'm here to help you out! Let's dive right in. ๐Ÿ’ช

The first thing we need to do is perform the request and store the response in a variable. In your case, it looks like you're already doing that with the mockMvc.perform(...) method. This is great, we're off to a good start! ๐ŸŽ‰

Next, we need to extract the response body from the MockHttpServletResponse object. This can be done using the getResponse().getContentAsString() method. This will give us the response body as a string that we can work with. ๐Ÿ“

Now that we have the response body as a string, we can compare it to the expected string using any method or assertions of your choice. In this case, you want to check if the response body contains the string "Username already taken".

Here's an example of how you can achieve this:

andExpect(content().string(containsString("Username already taken")))

You can add this assertion right after the andExpect(status().isBadRequest()) assertion. This will check if the response body contains the expected string and pass the test if it does. โœ…

Here's how your updated test method will look like:

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {
    mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
        .content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
        .andDo(print())
        .andExpect(status().isBadRequest())
        .andExpect(content().string(containsString("Username already taken")));
}

And that's it! You should now be able to check if a specific string is present in the response body using mockMvc. ๐ŸŽ‰

I hope this guide was helpful in solving your problem. If you have any further questions or need clarification, feel free to leave a comment below. Happy testing! ๐Ÿงช๐Ÿ’ป

Have you ever encountered a similar issue while testing with mockMvc? How did you solve it? Share your experiences in the comments below! โœจโœ๏ธ

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

๐Ÿ”ฅ ๐Ÿ’ป ๐Ÿ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! ๐Ÿš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings ๐Ÿ’ฅโœ‚๏ธ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide ๐Ÿš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? ๐Ÿค” Well, my