这是一个有效的解决方案。
关键是重写 JerseyTest 的 configureDeployment() 方法,并通过传递 Application 特定的 ResourceConfig.class 来创建 DeploymentContext,而不是重写 configure() 方法并返回 ResourceConfig 实例,以便测试容器正确初始化 guice-bridge。
这是以下版本的 Jersey、Guice 和 HK2 guice-bridge
<jersey.version>2.15</jersey.version>
<jackson2.version>2.4.4</jackson2.version>
<hk2.guice.bridge.version>2.4.0-b10</hk2.guice.bridge.version>
<guice.version>4.0-beta5</guice.version>
1)我的服务类
public interface MyService {
public void hello();
}
2)我的模拟服务实现
public class MyMockServiceImpl implements MyService{
public void hello() {
System.out.println("Hi");
}
}
3)我的资源类与 Guice 注入服务
@Path("myapp")
public class MyResource {
private final MyService myService;
@Inject
public MyResource(MyService myService) {
this.myService = myService;
}
}
4)我的资源测试类
public class MyResourceTest extends JerseyTestNg.ContainerPerClassTest {
@Override
protected Application configure() {
return null;
}
@Override
protected DeploymentContext configureDeployment() {
return DeploymentContext.builder(MyTestConfig.class).build();
}
// other test and setup/teardown methods
}
5) 资源配置类
static class MyTestConfig extends ResourceConfig {
@Inject
public MyTestConfig(ServiceLocator serviceLocator) {
packages("com.myapp.rest");
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(Guice.createInjector(new MyTestModule()));
}
}
6) 我的 Guice 测试模块类
public class MyTestModule implements Module {
@Override
public void configure(Binder binder) {
binder.bind(MyService.class)
.to(MyMockServiceImpl.class);
}
}