使用MockMvc post方法测试Spring Controller

时间:2018-04-21 13:22:30

标签: unit-testing spring-mvc spring-boot mockito mockmvc

我正在尝试在Spring Boot应用程序中测试我的控制器的方法。这是一个后端点,它在请求中获取一个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设置请求体?

3 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:2)

另一种方法(受@ stelios-anastasakis的回答启发)是在Content-Type标头中提供字符编码:

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

请注意,我们在这里使用MediaType.APPLICATION_JSON_UTF8_VALUE而不是MediaType.APPLICATION_JSON

答案 2 :(得分:0)

您肯定错过了方法参数的注释。

public @ResponseBody ResponseEntity<String> deleteByMessageId(String id)

应该是这样的:

public @ResponseBody ResponseEntity<String> deleteByMessageId(@RequestParam("id") String id)

如果要将其用作请求参数。

看看Spring MVC documentation here。 当然,编写测试取决于你对id的期望。