2011-07-13

Testing JPA

I'm developing my own JEE project (more info soon, source code will be available) and while it's not going to be a vanilla JEE application, I intend not to use Spring. I reached the phase of writing JPA entities and wanted to test them, their associations and operations on them, using an embedded database. Turns out, it's not so obvious. What I wanted is to have my @PersistenceContext injected without having to run those tests on an embedded/stand-alone application server.

And Spring does it so nicely...

I talked to Adam Bien and Jacek Laskowski about this.

Adam's solution


Adam suggested I take a look at his x-ray application. What he does to test JPA is he instantiates EntitytManager himself for each @Test method.

           EntityManagerFactory entityManagerFactory = Persistence
                   .createEntityManagerFactory("testPu");
           entityManager = entityManagerFactory.createEntityManager();

He then sets this EntityManager on the DAO/repository directly (not using a setter), on a package-level exposed field. It will not work if your DAO/repository is instantiated by CDI - you must use a package-level exposed method. Then it works (proxying).

Still, I didn't quite like this solution because it forces you to expose a field/method you wouldn't otherwise expose, and because it doesn't reflect reality where @PersistenceContext is injected.

Jacek's solution


Jacek had a different approach. One that didn't require exposing the field. You can view his test.

What he does is he uses OpenEJB to inject @PersistenceContext.

I decided I didn't like the boilerplate and I began to wonder whether Arquillian could inject @PersistenceContext for me.

Arquillian


Unfortunately, it turned out that Arquillian does not inject @PersistenceContext. I asked Dan Allen and Aslak Knutsen about it.

I decided it would be best if I could see whether Arquillian could do this so I forked Arquillian's source code on GitHub and I'm currently playing with it. It looks promising, so who knows, maybe it will save some hassle and boilerplate!

No comments:

Post a Comment