Unitils provides an excellant infrastructure for unit testing DAO (and data-service) layers for Spring as IoC Framework on all the component unit testing frameworks such as JUnit 3, JUnit4 and TestNG, without any boilerplate code or coniguration hassles. We will look at establishing a testing infrastructure for Spring with JPA on TestNG frmaework.
Suppose the custom DAO and its implementation definition are like this (with regard to semantics of Spring JPA integration)
package mypackage;
public CustomDAO
{ public List findAll();
public void save(Entity eo);
}
package mypackage;
public CustomDAOImpl implements CustommmDAO
{ @PersistenceContext
private EntityManager em;
//all other method implementations..
....
}
In order to setup a Unitils test infrastructure on TestNG, the following is the class-template:
public class CustomDAOTestCase extends UnitilsTestNG
{ /**
* Injects a test specific application context configuration
*/
@SpringApplicationContext
public ConfigurableApplicationContext createApplicationContext()
{ return new ClassPathXmlApplicationContext("applicationContext-test.xml");
}
@SpringBean("customDAO")
private CustomDAO customDAO;
//all @Test annotated methods..
@Override
protected void unitilsAfterTestTearDown(java.lang.reflect.Method method)
{}
}
for which the following would be the test specific Spring’s application context confguration (applicationContext-test.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="entityManagerFactory" >
<property name="persistenceXmlLocation" value="persistence-test.xml"/>
<property name="persistenceUnitName" value="customservice-test"/>
</bean>
<bean id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="customDAO" class="mypackage.CustomDAOImpl"/>
</beans>
Look specifically at entityManagerFactory bean definition, org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean allows us to load test specific persistence.xml which could allow us to maintain more than onne persistence context for a sample application.
These two definitions extend the Spring’s JPA capabilities for unit testing DAO on Unitils infrastructure!