Following the advice from here Spring Boot Remove Whitelabel Error Page I created a custom error controller to return custom error response in json format which looks like
@RestController
public class CustomErrorController implements ErrorController {
private static final String PATH = "/error";
@Value("${spring.debug:false}")
private boolean debug;
@Autowired
private ErrorAttributes errorAttributes;
@RequestMapping(value = PATH)
ErrorJson error(HttpServletRequest request, HttpServletResponse response) {
return new ErrorJson(response.getStatus(), getErrorAttributes(request, debug));
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
}
@Override
public String getErrorPath() {
return PATH;
}
}
Where CustomErrorController
implements ErrorController
and ErrorJson
is just a simple class to format json error response.
Now I am trying to write a Test, to test if a nonexistent enpoint is hit the CustomErrorController handles it and returns a 404 with json response like:
{
"status": 404,
"error": "Not Found",
"message": "No message available",
"timeStamp": "Thu Jun 29 14:55:44 PDT 2017",
"trace": null
}
My test currently looks like
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomErrorControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void invalidURLGet() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/foo"))
.andExpect(status().is(404))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andReturn();
}
}
I get the error response with status 404
but the content body is null, with MockHttpServletResponse
as:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {X-Application-Context=[application:development:-1]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
So, I have 2 questions:
- Why is the content body is null. Is
MockMvc
not able to find theCustomErrorController
. - Am I testing the error behaviour incorrectly. If so how can I test the custom error response?