1

我正在尝试使用 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

欢迎任何帮助。

4

1 回答 1

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

}

你还需要一个beans.xmlsrc/test/resources/META-INF.

于 2016-04-13T11:31:28.660 回答