Integration testing for Spring 3 Controllers


A quick follow up post on writing integration tests for Spring 3 MVC controllers. For each controller class, we need to test:

  1. The request mapping annotations to ensure requests are wired properly to the intended methods.
  2. The request handling methods themselves.

This post will focus on how to test the request mappings.


The codes I use here is largely from this blog post. I have to make a couple of minor changes to get it running in my development environment (Spring 3.0.3). In particular, I have to explicitly get beans using AnnotationMethodHandlerAdapter and DefaultAnnotationHandlerMapping classes to avoid the following exception:

NoSuchBeanDefinitionException … expected single bean but found 2

Hence my codes are like the followings with the original line commented out:

 /* this.handlerAdapter = applicationContext.getBean(HandlerAdapter.class);


this.handlerAdapter = applicationContext.getBean(AnnotationMethodHandlerAdapter.class);


/* final HandlerMapping handlerMapping = applicationContext.getBean(HandlerMapping.class);


final HandlerMapping handlerMapping = applicationContext.getBean(DefaultAnnotationHandlerMapping.class);


To test the following controller method for create a new tag resource:

@RequestMapping(value=”/tag/add.action”, method=RequestMethod.PUT)
public String put(@Valid @ModelAttribute(“tag”) TagDTO tagDTO, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute(“errors”, result.toString());
return “admin/tag/error”;
// …
return “redirect:/admin/tags/list.action”;

I have to following 2 tests:

public void testCreateFail() throws Exception {
final ModelAndView mav = handle(request, response);
assertEquals(“admin/tag/error”, mav.getViewName());

public void testCreateOK() throws Exception {
request.addParameter(“name”, “tag name”);
final ModelAndView mav = handle(request, response);
assertEquals(“redirect:/admin/tags/list.action”, mav.getViewName());

The above should be rather self explanatory. Note that the HiddenHttpMethodFilter filter defined in the web.xml file to handle PUT/DELETE for RESTful requests is not invoked here and the PUT/DELETE methods have to be specified in the request’s setMethod() method explicitly as in the above examples.

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

One Response to Integration testing for Spring 3 Controllers

  1. Syed Khurram Anwar says:

    I am trying to run this code with Spring 3.0.3 and I have made the these changes as well but stil getting the exception

    No unique bean of type [org.springframework.web.servlet.HandlerMapping] is defined:

    Can you tell me what else I need to change in the code given on that blog