Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA-based JUnit Test Best Practices

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?

like image 273
mlaccetti Avatar asked Aug 05 '09 17:08

mlaccetti


People also ask

What is JPA and JUnit?

JPA allows you to define which objects are persisted and how they should be persisted in the Java applications. At first, JPA was introduced as an EJB 3.0 subset. Every EJB container contains a persistent layer that is defined by the JPA. Junit can be defined as the open-source framework for unit testing in Java.


1 Answers

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:

  • How to configure JPA for testing in Maven
  • Suggest a JPA Unit test framework
like image 176
Aaron Digulla Avatar answered Sep 18 '22 13:09

Aaron Digulla