2

I am trying to implement a litte integration test using Arquillian and Wildfly 8.2.
Persisting and finding via entity manager works, but using queries any kind doesn't find anything.

My test class:

@RunWith(Arquillian.class)
public class VoteServiceTest {    
  @Inject
  private EntityManager entityManager;

  @Before
  public void createEntityManager() {
    entityManager.persist(user);
    entityManager.persist(vote);
  }

  @Test
  public void justATest() {
    Assert.assertTrue(entityManager.find(User.class, 1L) != null); // Works
    Assert.assertTrue(entityManager.find(Vote.class, 4L) != null); // Works
    Assert.assertTrue(entityManager.createQuery("SELECT c FROM Vote c", Vote.class).getResultList() == 1); // Fails
  }

  @Deployment
  public static JavaArchive createDeployment() {
    return ShrinkWrap.create(JavaArchive.class).addPackages(true, "de/...")
            .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
  }
}

persistence.xml:

<persistence ...>
    <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
        <class>de....Vote</class>
        <class>de....User</class>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
            <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:test"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

What did I miss?

CSchulz
  • 10,882
  • 11
  • 60
  • 114

1 Answers1

2

The answer is quite simple, I have forgotten to use transactions. After changing the code, my queries returned the entities I was expecting.

  @PersistenceContext
  protected EntityManager em;

  @Inject
  protected UserTransaction utx;

  @Before
  public void preparePersistenceTest()
      throws Exception {

    utx.begin();
    em.joinTransaction();
    em.persist(user);
    em.persist(vote);
    utx.commit();
    // reset the persistence context (cache)
    em.clear();
  }
CSchulz
  • 10,882
  • 11
  • 60
  • 114