How to check String in response body with mockMvc
To check a string in the response body with MockMvc, you can use the andExpect() method of the MockMvcResultMatchers class.
To check a string in the response body with MockMvc, you can use the andExpect() method of the MockMvcResultMatchers class.
Here is an example of how to use MockMvcResultMatchers.andExpect() to check a string in the response body:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void checkExactStringInResponse() throws Exception {
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(content().string("user1, user2, user3"));
}
}In this example, the get() method of MockMvcRequestBuilders is used to send a GET request to the /users URL, and the andExpect() method is used to assert that the response has a 200 OK status and that the response body contains the exact string "user1, user2, user3". Note that content().string() performs an exact match, which may fail due to whitespace or JSON formatting differences. For more robust checks, consider using content().containsString():
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(content().containsString("user1"));You can also use the MockMvcResultMatchers.jsonPath() method to check a specific value in the response body using JSONPath. For example:
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.users[0].name").value("user1"));This example checks that the first element in the "users" array has a "name" property with the value "user1".