如何将依赖注入JerseyTest?

时间:2017-03-15 16:11:20

标签: java dependency-injection cdi jersey-2.0 jersey-test-framework

我想使用CDI将MyService直接注入我的JerseyTest。可能吗? MyServiceMyResource注入,但是当我尝试从MyJerseyTest访问它时,我得到NullPointerException。

public class MyResourceTest extends JerseyTest {

  @Inject
  MyService myService;

  private Weld weld;

  @Override
  protected Application configure() {
    Properties props = System.getProperties();
    props.setProperty("org.jboss.weld.se.archive.isolation", "false");

    weld = new Weld();
    weld.initialize();

    return new ResourceConfig(MyResource.class);
  }

  @Override
  public void tearDown() throws Exception {
    weld.shutdown();
    super.tearDown();
  }

  @Test
  public void testGetPersonsCount() {
    myService.doSomething();  // NullPointerException here

    // ...

  }

}

1 个答案:

答案 0 :(得分:1)

我认为您需要提供org.junit.runner.Runner的实例,您将在其中进行焊接初始化。此运行器还应负责为Test类的实例提供必要的依赖注入。一个例子如下所示

public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {  

private final Class<?> clazz;  
private final Weld weld;  
private final WeldContainer container;  

public WeldJUnit4Runner(final Class<Object> clazz) throws InitializationError {  
    super(clazz);  
    this.clazz = clazz;  
    // Do weld initialization here. You should remove your weld initialization code from your Test class.
    this.weld = new Weld();  
    this.container = weld.initialize();  
}  

@Override  
protected Object createTest() throws Exception {  
    return container.instance().select(clazz).get();    
}  
} 

您的Test类应使用@RunWith(WeldJUnit4Runner.class)进行注释,如下所示。

@RunWith(WeldJUnit4Runner.class)
public class MyResourceTest extends JerseyTest {

@Inject
MyService myService;

  // Test Methods follow
}