gpt4 book ai didi

java - 如何将依赖项注入(inject) JerseyTest?

转载 作者:行者123 更新时间:2023-11-30 10:32:13 26 4
gpt4 key购买 nike

我想使用 CDI 将 MyService 直接注入(inject)我的 JerseyTest。是否可以? MyService 已成功注入(inject)到 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

// ...

}

}

最佳答案

我认为您需要提供一个 org.junit.runner.Runner 实例,您将在其中进行焊接初始化。该运行器还应负责提供 Test 类的实例,并注入(inject)必要的依赖项。示例如下所示

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
}

关于java - 如何将依赖项注入(inject) JerseyTest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42815132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com