This repository has been archived by the owner on Jun 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
JPA + EJB 3 Testing
AlistairIsrael edited this page Apr 26, 2011
·
6 revisions
@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 ...
}
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();
}
}
@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();
}
}
Using junit-rules
to write a functional unit test that exercises WidgetServiceBean
(and JpaWidgetDao
) all we need to write is:
<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>
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>
@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!