【问题标题】:How to inject dependency into JerseyTest?如何将依赖项注入 JerseyTest?
【发布时间】:2017-08-06 12:13:01
【问题描述】:

我想使用 CDI 将 MyService 直接注入我的 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

    // ...

  }

}

【问题讨论】:

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


    【解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2023-01-04
      • 2011-11-22
      • 2011-06-12
      • 1970-01-01
      相关资源
      最近更新 更多