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

bar*_*ber 4 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>
Run Code Online (Sandbox Code Playgroud)

我在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;
   }
}
Run Code Online (Sandbox Code Playgroud)

以及使用此跑步者的单元测试.测试是注入一个应用程序范围的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
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗?

pal*_*int 6

看看CDI-Unit.它Runner为JUnit Test类生成一个:

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

    ...
}
Run Code Online (Sandbox Code Playgroud)

来源: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
Run Code Online (Sandbox Code Playgroud)