JPA-based JUnit Test Best Practices

mlaccetti picture mlaccetti · Aug 5, 2009 · Viewed 37.4k times · Source

This is a bit of an odd question, but it has been bothering me for a few months now. I have built a JPA-based web application using Wicket + Hibernate (built with Maven), and want to test the DAO layer directly. I created a specific src/test/resources/META-INF/persistence.xml file that I used for testing, but have been running into conflicts with WTP and the like. To get around these issues, I created a separate test project where the unit tests live. Is there a better way to manage unit tests for a JPA project without having duels between persistence files?

Addendum: Would other test frameworks (TestNG, for example) make this any easier?

Answer

Aaron Digulla picture Aaron Digulla · Aug 5, 2009

You may want to try mockito. The test works like this:

You use mockito to "implement" EntityManager. Instead of the real code, you use the methods of mockito to say "if the application calls getReference(), then return this object". In the background, mockito will create a proxy instance which intercepts the Java method calls and returns the values which you specify. Calls to other methods will return null.

Mocking things like createQuery() works the same way but you first need to create a mockup of Query and then use the same approach as in getReference() (return the query mockup).

Since you don't use a real EM, you don't need a real persistence.xml.

A much more simple solution would be if you could set some property to change the name of the persistence.xml file but I don't think that this is possible.

Some other links that may help: