gpt4 book ai didi

unit-testing - 使用 MockMvc post 方法进行 Spring Controller 测试

转载 作者:行者123 更新时间:2023-12-04 04:41:53 29 4
gpt4 key购买 nike

我正在尝试在 Spring Boot 应用程序中测试我的 Controller 的方法。这是一个 post 端点,它在请求中获取一个 id 并将此 id 传递给服务:

@Slf4j
@Controller
public class AdministrationController {

private final AdministrationService administrationService;

@Autowired
public AdministrationController(AdministrationService administrationService) {
this.administrationService = administrationService;
}

@PostMapping("/administration")
public @ResponseBody ResponseEntity<String> deleteByMessageId(String id) {
return new ResponseEntity<>(administrationService.deleteMessageById(id), HttpStatus.OK);
}
}

Controller 此方法的测试:
RunWith(SpringRunner.class)
@WebMvcTest(AdministrationController.class)
public class AdministrationControllerTest {

@Autowired
private MockMvc mvc;

@MockBean
private AdministrationService service;

@Test
public void
deleteByMessageId_whenCalled_thenServiceMethodIsCalledWithRequestParameters() throws Exception {

Object randomObj = new Object() {
public final String id = "1234";
};

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(randomObj);


MvcResult result = mvc.perform(
post("/administration")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isOk())
.andReturn();

verify(service, times(1)).deleteMessageById("1234");
}

}

当我运行此测试时,会执行 post 请求,但主体为空:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /administration
Parameters = {}
Headers = {Content-Type=[application/json]}
Body = <no character encoding set>
Session Attrs = {}

看来,即使我在测试中设置了内容,它也没有出现在我发送的请求中。
而且,确实,测试失败了:
Argument(s) are different! Wanted: "1234"
Actual invocation has different arguments: null

我在这里缺少什么?如何使用 MockMvc 设置请求正文?

最佳答案

尝试使用 .characterEncoding("utf-8")) :

MvcResult result = mvc.perform(post("/administration")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.characterEncoding("utf-8"))
.andExpect(status().isOk())
.andReturn();

关于unit-testing - 使用 MockMvc post 方法进行 Spring Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956208/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com