Skip to content
This repository has been archived by the owner on Jun 16, 2020. It is now read-only.

JPA + EJB 3 Testing

AlistairIsrael edited this page Apr 26, 2011 · 6 revisions

Let’s start with a somewhat typical JPA entity

@Entity
@NamedQuery(name = "Widget.listAll", query = "SELECT w FROM Widget w")
public class Widget implements Serializable {

  @Id
  private Long id;

  @Column
  private String name;

  // accessors ...

}

Add a common DAO

public class JpaWidgetDao implements WidgetDao {

  private final EntityManager em;

  public JpaWidgetDao(EntityManager em) {
    this.em = em;
  }

  public List<Widget> listAll() {
    Query query = em.createNamedQuery("Widget.listAll");
    return query.getResultList();
  }

}

Finally, let’s say we have a typical service or EJB 3 stateless session bean

@Stateless
public class WidgetServiceBean implements WidgetService {

  @PersistenceContext
  private EntityManager em;

  private WidgetDao widgetDao;

  @PostConstruct
  private void initializeDaos() {
    widgetDao = new JpaWidgetDao(em);
  }

  public List<Widget> getWidgets() {
    return widgetDao.listAll();
  }

}

The Shiny

Using junit-rules to write a functional unit test that exercises WidgetServiceBean (and JpaWidgetDao) all we need to write is:

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
  http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
  version="1.0">
  <persistence-unit name="test">
  </persistence-unit>
</persistence>

fixtures.xml

In DbUnit XmlDataSet format

<!DOCTYPE dataset SYSTEM "dataset.dtd">
<dataset>
  <table name="widget">
    <column>id</column>
    <column>name</column>
    <row>
      <value>1</value>
      <value>First widget</value>
    </row>
    <row>
      <value>2</value>
      <value>Second widget</value>
    </row>
  </table>
</dataset>

Finally, our unit test

@Fixtures("fixtures.xml")
public class WidgetServiceBeanTest {

  @Rule
  public HibernatePersistenceContext persistenceContext = new HibernatePersistenceContext();

  @Test
  public void testGetWidgets() {
    WidgetServiceBean widgetService = new WidgetServiceBean();
    persistenceContext.injectAndPostConstruct(widgetService);

    List<Widget> widgets = widgetService.getWidgets();
    assertEquals(2, widgets.size());
  }

}

Tada!