Block test response status code in spring controller

I try unit test to use the following method in the controller

@ExceptionHandler(ExceptionName.class) @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR) public String handleIOException(ExceptionName ex, HttpServletRequest request) { return "errors.messagepage"; } 

I can check the name of the returned view.

I also want to check the response status code. How can i do this?

+4
source share
2 answers

You cannot, not as a unit test. Annotation is a structure instruction and is not part of your executable code.

The only way to verify this is to download the DispatcherServlet source code as part of your test (indeed, an integration test) or deploy the application and test it over HTTP.

If you really want to do this in unit test, then consider installing the response code on the HttpServletResponse manually, instead of using the annotation:

 @ExceptionHandler(ExceptionName.class) public String handleIOException(ExceptionName ex, HttpServletRequest request, HttpServletResponse response) { response.setStatus(500) return "errors.messagepage"; } 
+5
source

Take a look at the following blog.

Spring MVC: Integration Testing Controllers

It details the context context of the servlet and WebApplicationContext from JUnit. Using this setting, I can check the set of answers using annotation on controller methods.

0
source

All Articles