Amadeu Cabanilles Amadeu Cabanilles - 1 year ago 227
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.setHeader("Location", to);
response.setHeader("Connection", "close");

and this is my Test class:

public void testInitGetForm() throws Exception {

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


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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download