3

我想MyService使用 CDI 直接注入我的 JerseyTest。是否可以?MyService已成功注入MyResource,但当我尝试从 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

    // ...

  }

}
4

1 回答 1

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
}
于 2017-03-17T09:07:37.107 回答