Issue
I use spring boot 2.7 and test with junit during the execution of the tests I get an error : the other tests work well.
controller
@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);
}
controllerTest
@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())));
}
the error : "Content type not set" yet in the test I indicate well the content-type : ".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)
for the test to be successful, what should I change?
Solution
The content type you've set is used for the request, but in your assertion you're checking for the content type which is returned in the response.
As you can see in the log, there is no content type or body set in the MockHttpServletResponse:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null Cookies = []
So there seems to be an issue with the returned object in your mocked result of
when(employeeService.save(employeeDto.toEmployee())).thenReturn(employee);
since the result of this will be rendered to a JSON object you're doing your assertions on.
Answered By - Stefan Billmaier
Answer Checked By - Timothy Miller (JavaFixing Admin)