Unit Testing using the Java Persistence API
By cwebster on Mar 16, 2007
I have been using the Java Persistence API recently and I wanted to create some unit tests which did not run against the target database. Java Db which is bundled with both Glassfish and Java SE 6 is ubiquitous in my environment and supports running in embedded mode. This combination makes it ideal for mocking the database environment for unit tests.
If you look at the persistence.xml (NetBeans has a wizard to generate entity classes from a database), you will notice some properties (the properties will vary depending on the provider you are using) of the following form:
<property name="toplink.jdbc.user" value="app"/>
<property name="toplink.jdbc.password" value="app"/>
<property name="toplink.jdbc.url" value="DataBaseConnectionString"/>
<property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
The properties shown above are based on the TopLink provider and specify how to connect to the database. I wanted to override these properties to use an embedded database connection in my unit tests. The Persistence class provides two static methods for getting an EntityManagerFactory one of which takes a Map. The properties in the map can be used to override the properties defined in the persistence.xml file. I used a different set of properties for the connection string, user, password, and driver to support an embedded database. I also added the following property to the map:
Which will create recreate the database using the annotations. As part of the JUnit test's setup method, I would override the persistence properties, then establish a known database baseline before executing the unit tests. The combination of the ability to override the persistence manager and use an embedded database provides a nice mechanism for a cleanroom testing environment.