Passing the application context object to classes in unit testing
While writing junits for unit/integration testing, many times we come across a scenario where the application context object is required for multiple reasons like to get bean objects, to listen to context events etc.
For example, a service invokes a controller which in-turn invokes a DAO class. We try to get a bean dependency by doing a look up for the beans configured in spring configuration xml files.
Configuration config =(Configuration)ContextLoader.getCurrentWebApplicationContext().getBean(“config”);
However, ContextLoader.getCurrentWebApplicationContext() would return null when we try to call this code from junit test class.
We can have the junit class (test class) implement ApplicationContextAware interface and override the setApplicationContext(ApplicationContext context) method to receive the context object. But, this context object will be available only to the junit class. The above call ContextLoader.getCurrentWebApplicationContext() would return a null as the context has not been passed on to the classes for testing.
To resolve this issue, we can use ‘MockWebApplicationContextLoader’. MockWebApplicationContextLoader is a Spring ContextLoader that establishes a mock Servlet environment and WebApplicationContext so that Spring MVC stacks can be tested from within JUnit.
Given below is a sample implementation where we can have a mocked web application context set and be passed through out the application.
MockServletContext msc = new MockServletContext(“”);
“/applicationContext-test.xml”); // Path of the spring configuration xml files. Can be seperated by space if there are more number of configuration files in the project.
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(msc);
The configuration xml files referred here are picked up from class path. It is a good practice to use different configuration files for testing purposes, in this way, the dependency injections also get tested.