これがうまくいった解決策です。
重要なのは、JerseyTest の configureDeployment() メソッドをオーバーライドし、configure() メソッドをオーバーライドして ResourceConfig インスタンスを返す代わりに、アプリケーション固有の ResourceConfig.class を渡すことによって DeploymentContext を作成することです。これにより、テスト コンテナーは 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 が注入されたサービスを含む私の Resource クラス
@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) ResourceConfig クラス
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);
}
}