【问题标题】:CDI in JUnit tests with Jersey Test Framework使用 Jersey 测试框架进行 JUnit 测试中的 CDI
【发布时间】:2019-01-04 14:34:42
【问题描述】:

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

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

我无法在我的测试中注入任何类,所以我使用标准构造函数来创建 RepositoryA 的新实例。对我有用。

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

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

【问题讨论】:

    标签: dependency-injection jersey cdi inject jersey-test-framework


    【解决方案1】:

    根据您使用的库的版本,在 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。下面是为名为@9​​87654322@ 的实体类注入存储库的示例:

    @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 字段中,用于查找所有带注释的类。
    • 不要忘记测试类路径的META-INF 中的beans.xml,以便设置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 服务器,以获得所有需要的依赖项。

    【讨论】:

    • 很好,给你加油。我可以在焊接 junit 中使用 EntityManagerFactory 等吗?
    • 是的,并创建一个生产者以注入一个EntityManager
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多