Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing response status code in spring controller

I am trying to unit test the following method in controller

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

I can test for the returned view name.

I also want to test for the Response Status code. How can I do that?

like image 700
Rajani Karuturi Avatar asked Oct 25 '11 11:10

Rajani Karuturi


1 Answers

You can't, not as a unit test. The annotation is an instruction to the framework, and isn't part of your executable code.

The only way to test this is to bootstrap a DispatcherServlet as part of your test (an integration test, really), or to deploy the application and test it over HTTP.

If you really want to do this in a unit test, then consider setting the response code on the HttpServletResponse manually, rather than using an annotation:

@ExceptionHandler(ExceptionName.class)
public String handleIOException(ExceptionName ex, HttpServletRequest request, HttpServletResponse response) {
  response.setStatus(500)
  return "errors.messagepage";
}
like image 152
skaffman Avatar answered Sep 20 '22 01:09

skaffman