2

我想使用CDI將MyService直接注入到我的JerseyTest中。可能嗎? MyService已成功注入MyResource,但當我嘗試從MyJerseyTest訪問它時,我得到NullPointerException。如何向JerseyTest注入依賴項?

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

我認爲您需要提供一個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();  
} 
} 

而且您的測試類應該@RunWith(WeldJUnit4Runner.class)來註釋,如下圖所示。

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

@Inject 
MyService myService; 

    // Test Methods follow 
}