users@glassfish.java.net

Unit Testing JPA

From: Jason Lee <lee_at_iecokc.com>
Date: Thu, 9 Nov 2006 16:54:19 -0600

If this isn't the right place to ask this, I apologize, but...
 
We have several EJB3-based apps (deployed to Glassfish :) using JPA for
which we're trying to write unit tests (JUnit 4, fwiw). The problem
we're running into is transaction management. My probably not quite
accurate understanding is that EJB3 automatically creates a transaction
when a method on the session bean is called (like I said, that's
probably not totally accurate, but that's the net effect we've seen :).
When we call the methods on the JPA-based DAOs from our JSE/unit test
environment, we're not getting this automatic transaction management.
 
What's the recommended way to handle this? In an app of mine, I ended up
extending the DAO for my test case, overriding the methods I'm testing
and putting em.getTransaction().begin(); and
em.getTransaction().rollback(); before and after the super call. While
this works, it *is* a little ugly, and another developer in the office
is not wanting to use that approach. Is there a better "best practices"
approach? Google's not been too helpful for me.
 
Thanks!
 
-----
Jason Lee, SCJP
Programmer/Analyst
http://www.iec-okc.com <http://www.iec-okc.com/>