[英]Why do we need to set the request body as a UTF-8 string when testing the POST method in mockmvc
I would like to know how to test POST method so I am reading this article and this test looks like this:我想知道如何测试 POST 方法,所以我正在阅读这篇文章,这个测试看起来像这样:
@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(asJsonString(new EmployeeVO(null, "firstName4", "lastName4", "email4@mail.com")))
content(String content)
from the documentation:文档中的
content(String content)
:
"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." “将请求正文设置为 UTF-8 字符串。如果提供了内容并且 contentType(MediaType) 设置为 application/x-www-form-urlencoded,则内容将被解析并用于填充请求参数 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")))
我不明白这行代码是做什么用的以及它到底做了什么: .content(asJsonString(new EmployeeVO(null, "firstName4", "lastName4", "email4@mail.com")))
Assume that your rest api expects a POST request with Json Body.假设您的 rest api 期望一个带有 Json Body 的 POST 请求。
The method content
expects a body as string and asJsonString
return a json string from the object EmployeeVO with helper ObjectMapper from Jackson library.方法
content
需要一个字符串作为主体, asJsonString
从 object EmployeeVO 中返回一个 json 字符串,并带有来自 Jackson 库的帮助器 ObjectMapper。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.