When it comes time to write unit tests for an application most likely then not there will be a scenario where the tests would have to communicate to a database backend. However, using the main database of the application during the unit tests run can pollute and corrupt the data so the recommended approach is to use a dedicated database just for the tests.
Provisioning and maintaining a full database like MySQL or PostgreSQL can have a bit of an overhead. For that regards the most suited database for unit tests is H2
The area where H2 excels is that it can be provisioned before the test suite run starts and at the end removed it since it is a in memory database.
Below are the steps necessary for configuring a OpenJPA Entity Manager Factory using the H2 driver:
##Add maven dependency
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.191</version> <scope>test</scope> </dependency>
##Create Data Source
PoolConfiguration props = new PoolProperties(); props.setUsername("test"); props.setPassword(""); props.setUrl("jdbc:h2:~/test"); props.setDriverClassName("org.h2.Driver"); dataSource = new DataSource(); dataSource.setPoolProperties(props);
##Create Entity Manager Factory
Properties jpaProps = new Properties(); jpaProps.put("openjpa.ConnectionFactory", dataSource); jpaProps.put("openjpa.Log", "log4j"); jpaProps.put("openjpa.ConnectionFactoryProperties", "true"); entityManagerFactory = Persistence.createEntityManagerFactory("myfactory", jpaProps);