Spring Boot MockMvc 测试 POST 请求 JSON 格式数据
以下是一个示例代码,用于进行 Spring Boot 的 MockMvc 测试,测试 POST 请求,发送 JSON 格式数据:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testCreateUser() throws Exception {
User user = new User();
user.setName('John');
user.setAge(30);
ObjectMapper objectMapper = new ObjectMapper();
String userJson = objectMapper.writeValueAsString(user);
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isOk())
.andExpect(jsonPath('$.name').value('John'))
.andExpect(jsonPath('$.age').value(30));
}
}
这里,我们创建了一个 UserControllerTest 类,并使用 @AutoConfigureMockMvc 注解自动配置了 MockMvc 对象。在测试方法中,我们创建了一个 User 对象,并使用 ObjectMapper 将其转化为 JSON 格式的字符串。然后,我们使用 MockMvc 对象发送 POST 请求,并验证响应的 HTTP 状态码为 200,且返回的 JSON 数据中的 name 和 age 属性值与我们预期的相同。
需要注意的是,我们在发送 POST 请求时,设置了请求头的 Content-Type 为 application/json,并将转化后的 JSON 字符串设置为请求的内容。这样,服务端就能正确解析请求的 JSON 数据。
原文地址: https://www.cveoy.top/t/topic/nIbU 著作权归作者所有。请勿转载和采集!