DeltaSpike测试控制 - 未找到持久性单元

时间:2016-04-12 22:09:15

标签: java unit-testing cdi deltaspike deltaspike-jpa

我正在尝试使用DeltaSpike测试控制模块为我正在开发的新maven应用程序创建集成测试

它正在部署在Wildfly 9实例上

一个简单的测试用例:

@RunWith(CdiTestRunner.class)
@TestControl(projectStage = ProjectStage.IntegrationTest.class)
public class EmpresaCrudIntegrationTestCase {

    private static final String NOME_NOVA_EMPRESA = "teste";

    @Inject private EmpresaService empresaService;

    @Test
    public void test() {
        Empresa empresa = empresaService.save(new Empresa(NOME_NOVA_EMPRESA));

        Assert.assertNotNull(empresa.getId());
        Assert.assertEquals(NOME_NOVA_EMPRESA, empresa.getNome());
        Assert.assertTrue(empresa.getAtivo());
    }

}

persistence.xml位于src/test/resources/META-INF内,如下所示:

<persistence version="2.0"
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_2_0.xsd">
    <persistence-unit name="medipop" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <non-jta-data-source>java:jboss/datasources/medipop-test</non-jta-data-source>

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
        </properties>

    </persistence-unit>
</persistence>

实体经理正在通过CDI制作人方法公开:

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

@Produces
@RequestScoped
public EntityManager create() {
    return this.entityManagerFactory.createEntityManager();
}

问题是EntityManagerFactory在创建EntityManager

时仍然为空

欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

您无法在运行(Java EE)容器外的测试中注入带有@PersistenceUnit的非托管(RESOURCE_LOCAL)entityManager。你需要查找,这是一个例子:

@ApplicationScoped
public class TestEntityManagerProducer {

  private EntityManager entityManager;
  private EntityManagerFactory emf;

  @PostConstruct
  public void initDB(){
    emf = Persistence.createEntityManagerFactory("medipop");
  }

  @Produces
  @RequestScoped
  public EntityManager produceEntityManager()
  {
    entityManager = emf.createEntityManager();
    return entityManager;
  }

  public void closeEntityManager(@Disposes EntityManager entityManager)
  {
    if (entityManager != null && entityManager.isOpen())
    {
      entityManager.close();
    }
  }

}

此外,您需要src/test/resources/META-INF中的 beans.xml