users@glassfish.java.net

Re: Unit Testing JPA

From: Cheng Fang <Cheng.Fang_at_Sun.COM>
Date: Thu, 09 Nov 2006 19:12:34 -0500

Hi Jason,

This is an interesting topic. One approach is to have an abstraction
layer on top of your testcases. This layer will adapt between your
testcases and the actual runtime environment (e.g., JavaEE, or JavaSE).
This way your tests can stay the same and this layer will discover the
effective runtime and apply the right transaction behavior. Your tests
will interface with this adaptive layer, rather than the actual JPA API.

-cheng

Jason Lee wrote:
> 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/>
>