我使用 spring boot 2.7 并在執行測驗期間使用 junit 進行測驗,但出現錯誤:其他測驗運行良好。
控制器
@PostMapping(value = "/employees")
public ResponseEntity<Employee> addEmployee(@Valid @RequestBody EmployeeDto employeeDto) {
Optional<Employee> employeeDb = employeeService.findByEmail(employeeDto.getEmail());
// must not exist in database
if (!employeeDb.isEmpty()) {
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
// convertion dto -> model
Employee employee = employeeDto.toEmployee();
return new ResponseEntity<>(employeeService.save(employee), HttpStatus.OK);
}
控制器測驗
@Test
void addEmployee() throws Exception {
when(employeeService.save(employeeDto.toEmployee())).thenReturn(employee);
when(employeeService.findByEmail(any(String.class))).thenReturn(Optional.of(employee));
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(employeeDto);
mockMvc.perform(
MockMvcRequestBuilders
.post(REST_URL)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("utf-8")
.content(json)
)
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstname", is(employee.getFirstname())))
.andExpect(jsonPath("$.lastname", is(employee.getLastname())))
.andExpect(jsonPath("$.email", is(employee.getEmail())));
}
錯誤:“內容型別未設定”但在測驗中我很好地指出了內容型別:“.contentType(MediaType.APPLICATION_JSON)”
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/employees/
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"74"]
Body = {"email":"[email protected]","firstname":"firstname1","lastname":"lastname1"}
Session Attrs = {}
Handler:
Type = com.acme.app1.controllers.EmployeeController
Method = com.acme.app1.controllers.EmployeeController#addEmployee(EmployeeDto)
Async:
Async started = false
Async result = null
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: Content type not set
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:37)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:70)
at org.springframework.test.util.AssertionErrors.assertNotNull(AssertionErrors.java:106)
為了測驗成功,我應該改變什么?
uj5u.com熱心網友回復:
您設定的內容型別用于請求,但在您的斷言中,您正在檢查回應中回傳的內容型別。
正如您在日志中看到的,在 MockHttpServletResponse 中沒有設定內容型別或正文:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
重定向的 URL = null Cookies = []
因此,您的模擬結果中回傳的物件似乎存在問題
when(employeeService.save(employeeDto.toEmployee())).thenReturn(employee);
因為這個結果將被呈現給一個 JSON 物件,你正在做你的斷言。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524058.html
標籤:爪哇春天测试朱尼特
