首页 > 解决方案 > 使用 Jersey 测试框架进行 JUnit 测试中的 CDI

问题描述

我们正在使用 Jersey 测试框架进行 API 测试。在测试模式下,我们在生产中使用 h2 数据库 mysql。到目前为止一切都很好。

现在我想为我们的存储库编写测试以检查数据是否正确写入数据库。

我不能在我的测试中注入任何类,所以我使用标准构造函数来创建 RepositoryA 的新实例。为我工作。

现在的问题是:RepositoryA 现在正在注入 RepositoryB 的一个实例。并且注入不适用于测试范围。

是否可以在这种环境中运行注入?

标签: dependency-injectionjerseycdiinjectjersey-test-framework

解决方案


根据您使用的库版本,在 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);
    }
 }

重要的部分是:

  • 放在@EnableWeldJUnit 测试类上。
  • @WeldSetup放置在一个字段上WeldInitiator,以查找所有带注释的类。
  • 不要忘记beans.xmlMETA-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 服务器,以获得所有需要的依赖项。


推荐阅读