2

MyServiceを私のJerseyTestにCDIを使って直接注入したい。出来ますか? MyServiceはsucccefullが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 
}