JBoss Community Archive (Read Only)

Arquillian Old

Testing JPA

In order to test JPA, you need both a database and a persistence unit. For the sake of example, let's assume we are going to use the default datasource provided by the container and that the tables will be created automatically when the persistence unit starts up. Here's a persistence unit configuration that satisfies that scenario.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
   <persistence-unit name="users" transaction-type="JTA">
         <property name="hibernate.hbm2ddl.auto" value="create-drop" />
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />

Now let's assume that we have an EJB session bean that injects a persistence context and is responsible for storing and retrieving instances of our domain class, User. We've catered it a bit to the test for purpose of demonstration.

public @Stateless class UserRepositoryBean implements UserRepository {
   @PersistenceContext EntityManager em;

   public void storeAndFlush(User u) {

   public List<User> findByLastName(String lastName) {
      return em.createQuery("select u from User u where u.lastName = :lastName")
         .setParameter("lastName", lastName)

Now let's create an Arquillian test to ensure we can persist and subsequently retrieve a user. Notice that we'll need to add the persistence unit descriptor to the test archive so that the persistence unit is booted in the test archive.

public class UserRepositoryTest extends Arquillian {
   public static JavaArchive createTestArchive() {
      return ShrinkWrap.create(JavaArchive.class, "test.jar")
         .addClasses(User.class, UserRepository.class, UserRepositoryBean.class)

   private static final String FIRST_NAME = "Agent";
   private static final String LAST_NAME = "Kay";

   private UserRepository userRepository;

   public void testCanPersistUserObject() {
      User u = new User(FIRST_NAME, LAST_NAME);

      List<User> users = userRepository.findByLastName(LAST_NAME);

      Assert.assertTrue(users.size() == 1);

      Assert.assertEquals(users.get(0).getLastName(), LAST_NAME);
      Assert.assertEquals(users.get(0).getFirstName(), FIRST_NAME);
JBoss.org Content Archive (Read Only), exported from JBoss Community Documentation Editor at 2020-03-10 12:18:46 UTC, last content change 2011-07-29 17:06:25 UTC.