Amadeu Cabanilles Amadeu Cabanilles - 1 month ago 23
Java Question

Mockito: check response Header and Status

I have this junit test using Mockito (an open source testing framework for Java released under the MIT License) in a The Spring Web model-view-controller (MVC) framework application
I have this methods in the controller:

@RequestMapping(value = { "/devices" } , method = { RequestMethod.GET, RequestMethod.POST} )
public void initGetForm(@ModelAttribute("searchForm") final SearchForm searchForm,
HttpServletRequest request,
HttpServletResponse response,
Locale locale) throws Exception {

String newUrl = request.getContextPath() + "/devices/" + locale;

if (locale !=null && isValid(locale)) {
newUrl = request.getContextPath() + "/devices/" + DEFAULT_LOCALE;
}

redirectPermanently (response, newUrl);

}




protected void redirectPermanently (HttpServletResponse response, String to) {

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", to);
response.setHeader("Connection", "close");
}


and this is my Test class:

@Test
public void testInitGetForm() throws Exception {

controller.initGetForm(emptySearchForm(), request, response, null);

}

@Before
public void setUpTest() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}


Is it possible to check the Header and Status of the response ?????

Answer

You can use instances of MockHttpServletResponse and MockHttpServletRequest from spring-test module. Pass them to your controller and then just check results using MockHttpServletResponse.getStatus() MockHttpServletResponse.containsHeader() methods.