Java Reference
In-Depth Information
Testing with Spring and Injected Mock Objects
The tests that we've written so far involve the complete application,
including Stripersist, JPA, Hibernate, and the HSQLDB database. It's
good to be able to test everything, but it also makes our tests depend
on the complete chain being up and running. It'd be nice to be able to
test certain things even if, say, the database isn't available.
We were previously using a set of mock DAOs to simulate a database.
We can bring those back and use them so that tests become indepen-
dent of the database and the persistence layer. Doing this is easy with
the Spring dependency injection version of the application that we cre-
ated in Section 12.2 , Dependency Injection with Spring, on page 261 .
First, we reconfigure the extension packages in the Stripes filter, remov-
ing Stripersist and adding the Stripes interceptor for Spring DI:
Download email_27/src/stripesbook/test/stripesmock/ContactFormActionBeanTest.java
params.put("Extension.Packages", "stripesbook.ext,"
+ "net.sourceforge.stripes.integration.spring");
Next, we create a separate Spring configuration file, applicationContext-
test.xml , for which we use the mock DAO package:
Download email_27/web/WEB-INF/applicationContext-test.xml
<beans xmlns="http://www.springframework.org/schema/beans"
...>
<context:component-scan base-package="stripesbook.dao.mock"/>
</beans>
By telling Spring to use applicationContext-test.xml instead of the default
applicationContext.xml , Spring will load the mock DAOs instead of their
Stripersist counterparts. Configuring a different Spring configuration
file is done with the contextConfigLocation context parameter:
Download email_27/src/stripesbook/test/stripesmock/ContactFormActionBeanTest.java
mockServletContext.addInitParameter("contextConfigLocation",
"/WEB-INF/applicationContext-test.xml");
ContextLoaderListener springContextLoader =
new ContextLoaderListener();
springContextLoader.contextInitialized(
new ServletContextEvent(mockServletContext));
Notice that after adding the context parameter, we added the Spring
context loader listener as well, just like we had to do in the web.xml file.
The tests we wrote previously can be run without any change. The dif-
ference is that this version allows the tests to execute independently of
 
 
 
Search WWH ::




Custom Search