I would like to know how to test POST method so I am reading this article and this test looks like this:
@Test
public void createEmployeeAPI() throws Exception
{
mvc.perform( MockMvcRequestBuilders
.post("/employees")
.content(asJsonString(new EmployeeVO(null, "firstName4", "lastName4", "email4@mail.com")))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(MockMvcResultMatchers.jsonPath("$.employeeId").exists());
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I don't understand what this line of code is for and what exactly it does: .content(asJsonString(new EmployeeVO(null, "firstName4", "lastName4", "email4@mail.com")))
content(String content)
from the documentation:
"Set the request body as a UTF-8 String. If content is provided and contentType(MediaType) is set to application/x-www-form-urlencoded, the content will be parsed and used to populate the request parameters map."
I don't understand what this line of code is for and what exactly it does: .content(asJsonString(new EmployeeVO(null, "firstName4", "lastName4", "email4@mail.com")))
Assume that your rest api expects a POST request with Json Body.
The method content
expects a body as string and asJsonString
return a json string from the object EmployeeVO with helper ObjectMapper from Jackson library.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.