javadependency-injectioncdijersey-2.0jersey-test-framework

How to inject dependency into JerseyTest?


I want to inject MyService directly into my JerseyTest using CDI. Is it possible? MyService is succcefull injected into MyResource but I get NullPointerException when I try to access it from MyJerseyTest.

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

    // ...

  }

}

Solution

  • I think you need to provide an instance of org.junit.runner.Runner where you will do the weld initialization. This runner should also be responsible for providing an instance of your Test class with necessary dependencies injected. An example is shown below

    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();    
    }  
    } 
    

    And your Test class should be annotated with @RunWith(WeldJUnit4Runner.class) as shown below.

    @RunWith(WeldJUnit4Runner.class)
    public class MyResourceTest extends JerseyTest {
    
    @Inject
    MyService myService;
    
      // Test Methods follow
    }