gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:04:04 24 4
gpt4 key购买 nike

我正在尝试使用 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());
}

}

我有一个位于 src/test/resources/META-INF 内的 persistence.xml,如下所示:

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

问题是在创建EntityManagerEntityManagerFactory保持为空

欢迎任何帮助。

最佳答案

您无法在 (Java EE) 容器外部运行的测试中使用 @PersistenceUnit 注入(inject)非托管 (RESOURCE_LOCAL) 实体管理器。你需要查找,这里是一个例子:

@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

关于java - DeltaSpike 测试控制 - 未找到持久性单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36584938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com