4

我有一个用于单元测试的 Maven 项目,并且想使用 CDI。我将weld-se依赖项放在pom.xml中,如下所示:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
</dependency>
<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se</artifactId>
    <version>1.1.8.Final</version>
</dependency>
<dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>1.0-SP3</version>
</dependency>

我在 JUnit 测试运行器中引导焊接:

public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
   private final Class klass;
   private final Weld weld;
   private final WeldContainer container;

   public WeldJUnit4Runner(final Class klass) throws InitializationError {
       super(klass);
       this.klass = klass;
       this.weld = new Weld();
       this.container = weld.initialize();
   }

   @Override
   protected Object createTest() throws Exception {
       final Object test = container.instance().select(klass).get();

       return test;
   }
}

还有一个使用这个运行器的单元测试。该测试正在注入一个应用程序范围的 bean。问题是由于对唯一注入点的“不满足的依赖关系”,焊接无法初始化,就好像我的应用程序范围的 bean 完全未知焊接一样。但是那个 bean 在我的测试中位于 src/test/java/... 中(但在另一个 java 包中)。

我在 src/test/resources 中有一个空的 beans.xml。

我注意到weld在启动时会发出警告,但我认为这些不是我的问题的原因:

604 [main] WARN org.jboss.weld.interceptor.util.InterceptionTypeRegistry - Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
605 [main] WARN org.jboss.weld.interceptor.util.InterceptionTypeRegistry - Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled

有人可以帮我吗?

4

3 回答 3

6

看看CDI-Unit。它Runner为 JUnit 测试类提供了一个:

@RunWith(CdiRunner.class) // Runs the test with CDI-Unit
class MyTest {
    @Inject
    Something something; // This will be injected before the tests are run!

    ...
}

来源:CDI-Unit 用户指南

CDI-Unit 还会记录以下警告,但尽管它运行良好:

WARN (InterceptionTypeRegistry.java) - WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled
WARN (InterceptionTypeRegistry.java) - WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled
于 2014-03-18T08:56:12.907 回答
4

需要注意的几件事:用于ArquillianDeltaSpike CdiCtrl 模块的 Weld SE 容器

于 2012-10-26T04:48:02.013 回答
1

Add the following beans.xml to the src/test/resources/META-INF directory:

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    version="1.1" bean-discovery-mode="all">
</beans>

The reason for the warnings: Classes javax.ejb.PostActivate and javax.ejb.PrePassivate were not found. You are missing a dependency.

Add this dependency to your pom.xml:

<dependency>
    <groupId>javax.ejb</groupId>
    <artifactId>javax.ejb-api</artifactId>
    <version>3.2</version>
</dependency>

Regards.

于 2015-08-30T17:13:11.923 回答