dependency-injection - 使用 Jersey 测试框架进行 JUnit 测试中的 CDI
问题描述
我们正在使用 Jersey 测试框架进行 API 测试。在测试模式下,我们在生产中使用 h2 数据库 mysql。到目前为止一切都很好。
现在我想为我们的存储库编写测试以检查数据是否正确写入数据库。
我不能在我的测试中注入任何类,所以我使用标准构造函数来创建 RepositoryA 的新实例。为我工作。
现在的问题是:RepositoryA 现在正在注入 RepositoryB 的一个实例。并且注入不适用于测试范围。
是否可以在这种环境中运行注入?
解决方案
根据您使用的库版本,在 JUnit Test 中运行 CDI 会有所不同。
首先你需要添加这个依赖,选择正确的版本:
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-junit5</artifactId> // or weld-junit4
<version>1.3.0.Final</version>
<scope>test</scope>
</dependency>
然后您可以在您的 JUnit 测试中启用 Weld。这是一个为名为 的实体类注入存储库的示例VideoGame
:
@Slf4j
@EnableWeld
class VideoGameRepositoryTest
{
@WeldSetup
private WeldInitiator weld = WeldInitiator.performDefaultDiscovery();
@Inject
private VideoGameRepository repo;
@Test
void test()
{
VideoGame videoGame = VideoGameFactory.newInstance();
videoGame.setName("XENON");
repo.save(videoGame);
// testing if the ID field had been generated by the JPA Provider.
Assert.assertNotNull(videoGame.getVersion());
Assert.assertTrue(videoGame.getVersion() > 0);
log.info("Video Game : {}", videoGame);
}
}
重要的部分是:
- 放在
@EnableWeld
JUnit 测试类上。 @WeldSetup
放置在一个字段上WeldInitiator
,以查找所有带注释的类。- 不要忘记
beans.xml
在META-INF
您的测试类路径中设置discovery-mode
. @Slf4j
是一个 lombok 注释,你不需要它(除非你已经在使用 Lombok)
这里的VideoGameRepository
实例也有利于注入,就像在经典的 CDI 项目中一样。
这是获取标有范围VideoGameFactory
的实体类的全新实例的代码。@Dependent
该工厂以编程方式调用 CDI 当前上下文。
public class VideoGameFactory
{
public static VideoGame newInstance()
{
// ask CDI for the instance, injecting required dependencies.
return CDI.current().select(VideoGame.class).get();
}
}
或者,您可以查看Arquillian,它可以配备完整的 Java EE 服务器,以获得所有需要的依赖项。
推荐阅读
- c# - 使用 C# 的非 WPF 或 Win32 应用程序的 UI 自动化
- javascript - javascript中require()函数的问题
- java - 具有多个线程的 Kafka Producer - Java
- kubernetes - 同一命名空间中的两个 Kubernetes 部署无法通信
- aws-sam - API 网关通过 SAM 直接连接到 SNS
- neo4j - EXISTS 带有动态标签的密码查询
- javascript - 我如何粗略地匹配 Javascript 中的两个字符串?
- java - 如何从 JobService 中调用 fusedLocationClient.getLastLocation()?
- python - 比较数据框中特定列行的长度,python
- jquery - onchange 事件未在 flatpickr() 输入上唤醒