Spring MVC Integration Tests

An approach to Integration Testing the controllers in Spring MVC is to use the Integration Test support provided by Spring.

With Junit4 this support consists of a custom Junit Runner called the SpringJunit4ClassRunner, and a custom annotation to load up the relevant Spring configuration.

A sample Integration test would be along these lines:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/META-INF/spring/webmvc-config.xml", "contextcontrollertest.xml"})
public class ContextControllerTest {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;
    
    ......
 
 @Test
 public void testContextController() throws Exception{
  MockHttpServletRequest httpRequest = new MockHttpServletRequest("POST","/contexts");
  httpRequest.addParameter("name", "context1");
  
  httpRequest.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE,new FlashMap());
  MockHttpServletResponse response = new MockHttpServletResponse();
  Authentication authentication = new UsernamePasswordAuthenticationToken(new CustomUserDetails(..), null);
  SecurityContextHolder.getContext().setAuthentication(authentication);

  Object handler = this.handlerMapping.getHandler(httpRequest).getHandler();
  ModelAndView modelAndView = handlerAdapter.handle(httpRequest, response, handler);
  assertThat(modelAndView.getViewName(), is("redirect:/contexts"));
 }
}

I have used a MockHttpServletRequest to create a dummy POST request to a “/contexts” uri, and added some authentication details for Spring Security related details to be available in the Controller. The ModelAndView returned by the controller is being validated to make sure the returned view name is as expected.

A better way to perform a Controller related integration is using a relatively new Spring project called Spring-test-mvc , which provides a fluent way to test the controller flows. The same tests as above look like the following with Spring-test-mvc:

@Test
public void testContextController() throws Exception{
 Authentication authentication = new UsernamePasswordAuthenticationToken(new CustomUserDetails(..), null);
 SecurityContextHolder.getContext().setAuthentication(authentication);
 
 xmlConfigSetup("classpath:/META-INF/spring/webmvc-config.xml", "classpath:/org/bk/lmt/web/contextcontrollertest.xml").build()
  .perform(post("/contexts").param("name", "context1"))
  .andExpect(status().isOk())
  .andExpect(view().name("redirect:/contexts"));
}

The test has now become much more concise and there is no need to deal directly with a MockHttpServletRequest and MockHttpServletResponse instances and reads very well.

I have a little reservation about the amount of static imports and the number of function calls that are involved here, but again like everything else it is just a matter of getting used to this approach of testing.

Resources under WEB-INF location can also be used with spring-test-mvc, this way:

xmlConfigSetup("/WEB-INF/spring/webmvc-config.xml","classpath:/org/bk/lmt/web/contextcontrollertest.xml")
 .configureWebAppRootDir("src/main/webapp", false).build()
 .perform(post("/contexts").param("name", "context1"))
 .andExpect(status().isOk())
 .andExpect(view().name("redirect:/contexts"));
 
xmlConfigSetup("/WEB-INF/spring/webmvc-config.xml", "classpath:/org/bk/lmt/web/contextcontrollertest.xml")
 .configureWebAppRootDir("src/main/webapp", false).build()
 .perform(get("/contexts"))
 .andExpect(status().isOk())
 .andExpect(view().name("contexts/list"));

Reference: Spring MVC Integration Tests from our JCG partner Biju Kunjummen at the all and sundry blog.

Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

Leave a Reply


8 − four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close