2017-08-29 83 views
0

我是jUnit测试的新手。我有一个请求来测试一个拥有@RequestBody对象的方法。从搜索引擎优化中搜索了近4个小时,但无法找到它。我也读过类似的问题从堆栈,但没有解决我的问题。从jUnit春季测试中调用@RequestBody

我的测试控制器:

@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

你应该添加EmployeeRequest类型的请求主体。

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