我被困在一個控制器單元測驗 put 方法上,它總是回傳一個空的主體回應。
下面是我的代碼:
EmployeeServiceImpl.class
@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);
}
EmployeeController.class 有 @RequestMapping("/api/employees")
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employee) {
return new ResponseEntity<>(employeeService.updateEmployee(id, employee), HttpStatus.OK);
}
EmployeeControllerTest.class
@Test
public void givenUpdatedEmployee_whenUpdateEmployee_thenReturnUpdatedEmployee() throws Exception {
Long employeeId = 1L;
Employee savedEmployee = Employee.builder()
.id(employeeId)
.firstName("Jay")
.lastName("Lai")
.email("[email protected]")
.build();
Employee updatedEmployee = Employee.builder()
.id(employeeId)
.firstName("Jayyy")
.lastName("Laiii")
.email("[email protected]")
.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":"[email protected]"}
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"**
uj5u.com熱心網友回復:
問題就在這里
BDDMockito.given(employeeService.updateEmployee(employeeId, updatedEmployee))
因為您通過 Controller 的 PUT 請求正文是 a JSON,而不是Employee. 換句話說,您在 test 類中指定的 與
inupdatedEmployee不匹配,因此該陳述句無法按您的預期作業。結果,您得到了一個空的回應正文。employeeEmployeeServiceImplgiven...when...
您應該將您的given...when...宣告修改為
BDDMockito.given(employeeService.updateEmployee(eq(employeeId), any()))
那么它將正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470384.html
上一篇:無法加載模塊“專案名稱”
