我被一个控制器单元测试put方法卡住了,它总是返回一个空体响应.
下面是我的代码:
雇员服务公司.班
@Override
public Employee updateEmployee(Long id, Employee employee) {
Employee existingEmployee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("employee with id: " + id + " does not exist."));
existingEmployee.setFirstName(employee.getFirstName());
existingEmployee.setLastName(employee.getLastName());
existingEmployee.setEmail(employee.getEmail());
return employeeRepository.save(existingEmployee);
}
雇员控制员.具有@RequestMapping("/api/employees")的类
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employee) {
return new ResponseEntity<>(employeeService.updateEmployee(id, employee), HttpStatus.OK);
}
员工控制测试.班
@Test
public void givenUpdatedEmployee_whenUpdateEmployee_thenReturnUpdatedEmployee() throws Exception {
Long employeeId = 1L;
Employee savedEmployee = Employee.builder()
.id(employeeId)
.firstName("Jay")
.lastName("Lai")
.email("jay@gmail.com")
.build();
Employee updatedEmployee = Employee.builder()
.id(employeeId)
.firstName("Jayyy")
.lastName("Laiii")
.email("jayyy@gmail.com")
.build();
BDDMockito.given(employeeService.getEmployeeBYId(employeeId))
.willReturn(savedEmployee);
BDDMockito.given(employeeService.updateEmployee(employeeId, updatedEmployee))
.willReturn(updatedEmployee);
ResultActions response = mockMvc.perform(MockMvcRequestBuilders.put("/api/employees/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(updatedEmployee)));
response.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.firstName", CoreMatchers.is(updatedEmployee.getFirstName())))
.andExpect(MockMvcResultMatchers.jsonPath("$.lastName", CoreMatchers.is(updatedEmployee.getLastName())))
.andExpect(MockMvcResultMatchers.jsonPath("$.email", CoreMatchers.is(updatedEmployee.getEmail())));
}
这是输出.
我真的不明白我错过了什么,任何帮助都将不胜感激,谢谢.
MockHttpServletRequest:
HTTP Method = PUT
Request URI = /api/employees/1
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"73"]
Body = {"id":1,"firstName":"Jayyy","lastName":"Laiii","email":"jayyy@gmail.com"}
Session Attrs = {}
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
**java.lang.AssertionError: No value at JSON path "$.firstName"**