在春天从jUnit测试中调用@RequestBody

时间:2017-08-29 11:43:22

标签: spring-boot junit

我是jUnit test的新手。我有一个请求来测试一个有@RequestBody对象的方法。从goodle搜索了近4个小时但是找不到它。我也从堆栈中读到了类似的问题,但这并没有解决我的问题

我的测试控制器:

@Test
public void testInsertRequest() throws Exception {
    mockMvc.perform(post("http://localhost:8081/requests/add"))
            .andExpect(jsonPath("$.date").value("2017-08-09")).andExpect(jsonPath("$.orderPerson").value("Nermin"))
            .andExpect(jsonPath("$.orderPhone").value("0777675432")).andExpect(jsonPath("$.client").value("Nezrin"))
            .andExpect(jsonPath("$.clientPhone").value("0776763254")).andExpect(jsonPath("$.department").value("IT"))
            .andExpect(jsonPath("$.route").value("Neriman Nerimanov"));

}

我要测试的方法:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String insertRequest(@RequestBody EmployeeRequest employeeRequest) {
    System.out.println(employeeRequest.getDate());
    requestService.insertRequest(employeeRequest);   
}

我收到此错误:Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing。那么如何从junit @RequestBody

拨打电话

1 个答案:

答案 0 :(得分:2)

您应该添加EmployeeRequest类型的请求正文。

EmployeeRequest employeeRequest = new EmployeeRequest(...);
String body = (new ObjectMapper()).valueToTree(employeeRequest).toString();
mockMvc.perform(post("http://localhost:8081/requests/add"))
        .content(body)
        .andExpect ...