I have a problem with tests for 404 and 415 responses.
I made custom JSON responses for both, I can see JSON response in Postman, but It seems like it is not presented in tests.
application.properties
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false
ControllerAdvice
...
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
@ExceptionHandler(NoHandlerFoundException.class)
public ErrorResponseDTO notFoundMethod() {
return new ErrorResponseDTO("Endpoint not found.");
}
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(UnsupportedMediaTypeStatusException.class)
public ErrorResponseDTO notSupportedMedia() {
return new ErrorResponseDTO("Wrong request media type.");
}
...
TestClass
...
@Test
@Order(1)
public void endpointNotFound() throws Exception {
mockMvc
.perform(post("/user/logi"))
.andExpect(status().is(404));
//.andExpect(jsonPath("$.message", is("Endpoint not found."))); // <-- not working, saying that No value at JSON path "$.message"
}
...
Or when I use TestRestTemplate() I am able to get that response message
TestClass
...
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<ErrorResponseDTO> errorResponse = testRestTemplate
.getForEntity("http://0.0.0.0:4004/user/logi", ErrorResponseDTO.class);
...
BUT WHY I am unable to get it with MockMVC ???