Unit Testing using the Java Persistence API

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:

 <properties>
      <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"/>
  </properties>

 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:

 properties.put("toplink.ddl-generation","drop-and-create-tables";);

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.

 



Comments:

Make your life even simpler: use TestNG and Guice...

Posted by guest on March 19, 2007 at 02:46 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

cwebster

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today