如何在JUnit测试中引导焊接se

时间:2012-10-25 19:54:24

标签: java junit cdi weld

我有一个用于单元测试的maven项目,并且想要使用CDI。我把焊接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。

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

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

有人可以帮我吗?

3 个答案:

答案 0 :(得分:6)

看看CDI-Unit。它为JUnit Test类生成Runner

@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 user guide

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

答案 1 :(得分:4)

要注意的事项:ArquillianDeltaSpike CdiCtrl module的焊接SE容器

答案 2 :(得分:1)

将以下beans.xml添加到src/test/resources/META-INF目录:

<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>

警告的原因:未找到类javax.ejb.PostActivatejavax.ejb.PrePassivate。你错过了依赖。

将此依赖项添加到您的pom.xml:

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

问候。

相关问题