使用MockMvc post方法测试Spring Controller [英] Spring Controller testing with MockMvc post method
问题描述
我正在尝试在Spring Boot应用程序中测试控制器的方法.这是一个发布端点,它在请求中获取一个ID,并将该ID传递给服务:
I am trying to test a method of my controller in a Spring Boot application. This is a post endpoint, which gets an id in a request and it passes on this id to a service:
@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);
}
}
控制器的此方法的测试:
The test for this method of the 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");
}
}
运行此测试时,将执行发布请求,但正文为空:
When I run this test, the post request is executed, but with an empty body:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /administration
Parameters = {}
Headers = {Content-Type=[application/json]}
Body = <no character encoding set>
Session Attrs = {}
看来,即使我在测试中设置了内容,它也没有出现在我发送的请求中. 而且确实,测试失败:
It seems, even though I set the content in my test, it does not appear in the request I am sending. And, indeed, the test fails:
Argument(s) are different! Wanted: "1234"
Actual invocation has different arguments: null
我在这里想念什么?如何使用MockMvc设置请求正文?
What am I missing here? How can I set the request body with MockMvc?
推荐答案
尝试使用.characterEncoding("utf-8"))
:
MvcResult result = mvc.perform(post("/administration")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.characterEncoding("utf-8"))
.andExpect(status().isOk())
.andReturn();
这篇关于使用MockMvc post方法测试Spring Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!