Testing MVC (mode view controller) architecture based Spring application is very easy thanks to the mock testing framework provided by Spring. Without starting the server, controller code and service layer code can be tested. This tutorial is intended for Spring2.5(x) or later.
Please download source code from here. Download the two classes into your project (place them under a test folder to distinguish them from the source code). MockWebApplicationContextTestCase.java is the main class where all the magic happens. Inherit this class and you will be ready. SanityTest.java is provided as an example test class that makes use of MockWebApplicationContextTestCase.java to test a Controller class.
Requirements:
- Spring jars required to implement MVC application.
- Spring-test.jar - contains all the main classes required for Mock testing.
- Junit4 jar - Please note that when integrating Spring 2.5.x with Junit and use SpringJUnit4ClassRunner.class as the runner class for Junit, it has been found that Junit 4.4 was the compatible version. For Spring 3.x, Junit 4.5 or later can be used.
Explanation:
- First, we need access to ApplicationContext object of Spring to get hold all the objects defined in Spring definition files. As we are trying to test Spring MVC, it would be better to have access to GenericWebApplicationContext instead of GenericApplicationContext to have finer control over Web based Java objects like ServletRequest, ServletResponse, ServletContext objects. As a side note, Spring's TilesConfigurer class used for implementing tiles is only compliant with GenericWebApplicationContext (See E1 for details). In this Mock framework, we will be using MockServletRequest, MockServletResponse, MockServletContext classes provided by Spring.
- In the MockWebApplicationContextTestCase, you will see that it has been configured in such a way that any transaction is automatically rolled back thus preventing the corruption of data in the back end database.
- You will also be able to override a particular bean definition by having your own test spring bean configuration file and placing it on the class path. See @ContextConfiguration in that class.
Reference:
Errors/Warnings:
- (E1) java.lang.IllegalStateException: WebApplicationObjectSupport instance [org.springframework.web.servlet.view.tiles.TilesConfigurer@] does not run in a WebApplicationContext but in: org.springframework.context.support.GenericApplicationContext@ :