任何类型的查询都找不到持久化实体

时间:2015-01-21 12:39:25

标签: java-ee testing java-ee-7 wildfly-8 jboss-arquillian

我正在尝试使用Arquillian和Wildfly 8.2实现一个小小的集成测试 通过实体管理器保持和查找工作,但使用任何类型的查询都找不到任何东西。

我的测试班:

@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>

我错过了什么?

1 个答案:

答案 0 :(得分:2)

答案很简单,我忘了使用交易。更改代码后,我的查询返回了我期望的实体。

  @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();
  }