我尝试在Spring Boot应用程序中测试我的控制器的一个方法。这是一个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);
}
}
该方法对控制器的测试:
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设置请求主体?
4条答案
按热度按时间9njqaruj1#
尝试使用
.characterEncoding("utf-8"))
:j8ag8udp2#
另一个选项(受@stelios-anastasakis答案的启发)是在
Content-Type
报头中提供字符编码:请注意,这里我们使用
MediaType.APPLICATION_JSON_UTF8_VALUE
而不是MediaType.APPLICATION_JSON
。qlfbtfca3#
but5z9lq4#
您肯定遗漏了方法参数的注解。
应该是这样的:
如果要将其用作请求参数。
请看这里的Spring MVC文档。当然,编写测试取决于您对这里的id的期望。