JPA: Testing

You can test your JPA code by setting aside another folder structure, test/ for example, with a META-INF/ directory with a new persistence.xml file there pointing to a different database.

Here's new new persistence.xml:

 <?xml version="1.0" encoding="UTF-8" ?>
 <persistence xmlns:xsi=""
   <persistence-unit name="example" transaction-type="RESOURCE_LOCAL">
       <property name="javax.persistence.jdbc.driver" value="org.sqlite.JDBC" />
       <property name="javax.persistence.jdbc.url" value="jdbc:sqlite:/home/YOURUSERNAME/test.db" />
       <property name="eclipselink.logging.level" value="ALL" />
       <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

The only different to the previous ones is that we're putting our database in a new location - one where the runner of the junit test has write access. And we're doing drop-and-create-tables in the table creation.

The next thing you need is the junit4 file that calls the persistence provider to test adding of the entity:

public class JPAStarterTest {
  public void addAnotherThing() {
    // Arrange
    AnotherThing at = new AnotherThing();
    // Act
    // Assert
    assertNotNull("Id should not be null", at.getId());
    List<AnotherThing> list = em.createNamedQuery("listAll", AnotherThing.class).getResultList();
    assertEquals("Table has one entity", 1, list.size()); 
    assertEquals("Table has correcttext", "hii", list.get(0).getText());

  public static void beforeClass() {
    emf = Persistence.createEntityManagerFactory("exampletest");
    em = emf.createEntityManager();
  public static void afterClass() {

  public void before() {
    tx = em.getTransaction();
  private static EntityManagerFactory emf;
  private static EntityManager em;
  private EntityTransaction tx;	

Now when you run this, ensure your new persistence.xml is in the META-INF/ directory of the classes.

java java-junit java-jpa

Edit on github
comments powered by Disqus
Click me