문제

를 사용하여 HK2 의 guice-bridge 을 통합하는 저지 2.x 와 쥬스와 3.x.

public class MyApp extends ResourceConfig {

    @Inject
    public MyApp(ServiceLocator serviceLocator) {
        packages("com.mycompany");

        ...

        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
        guiceBridge.bridgeGuiceInjector(GuiceContext.INJECTOR);
    }
}

하지만 지금은 내가 저지 테스트를 더 이상 작동하지 않습니다.

public abstract class AbstractJerseyTest extends JerseyTest {

    public AbstractJerseyTest() throws TestContainerException {
        super(new InMemoryTestContainerFactory());
    }

    protected Application configure() {
        new MyApp(); // ERROR: missing 'ServiceLocator'
    }

}

그래서 나는 어디에 얻 ServiceLocator 한 단위 테스트?

도움이 되었습니까?

해결책 4

우리는 작업으로 도움의 그루비:

public class MemoryTestContainerFactory implements TestContainerFactory {

    private final Class<? extends Application> jaxrsApplicationClass;

    public MemoryTestContainerFactory(Class<? extends Application> jaxrsApplicationClass) {
        this.jaxrsApplicationClass = jaxrsApplicationClass;
    }

    @Override
    public TestContainer create(URI baseUri, DeploymentContext context) throws IllegalArgumentException {
        return new MemoryTestContainer(jaxrsApplicationClass, baseUri, context);
    }

    private static class MemoryTestContainer implements TestContainer {

        private final URI baseUri;
        private final ApplicationHandler appHandler;
        private final AtomicBoolean started = new AtomicBoolean(false);

        private static final Logger LOGGER = Logger.getLogger(MemoryTestContainer.class.getName());

        MemoryTestContainer(Class<? extends Application> jaxrsApplicationClass, URI baseUri, DeploymentContext context) {
            this.baseUri = UriBuilder.fromUri(baseUri).path(context.getContextPath()).build();    
            this.appHandler = new ApplicationHandler(jaxrsApplicationClass);
        }

        @Override
        public ClientConfig getClientConfig() {
            def provider = new InMemoryConnector.Provider(baseUri, appHandler) // private access (only works with Groovy)
            return new ClientConfig().connectorProvider(provider);
        }

        @Override
        public URI getBaseUri() {
            return baseUri;
        }

        @Override
        public void start() {
            if (started.compareAndSet(false, true)) {
                LOGGER.log(Level.FINE, "Starting InMemoryContainer...");
            } else {
                LOGGER.log(Level.WARNING, "Ignoring start request - InMemoryTestContainer is already started.");
            }
        }

        @Override
        public void stop() {
            if (started.compareAndSet(true, false)) {
                LOGGER.log(Level.FINE, "Stopping InMemoryContainer...");
            } else {
                LOGGER.log(Level.WARNING, "Ignoring stop request - InMemoryTestContainer is already stopped.");
            }
        }
    }
}

그것은 꽤 있지만,그것은 작동합니다.

다른 팁

어쩌면 청소기는 방법은 단순히 사용 Feature 와 구성 bridge 대신에 ResourceConfig

public class GuiceFeature implements Feature {

    public void configure(FeatureContext context) {
        ServiceLocator serviceLocator = ServiceLocatorProvider.getServiceLocator(context);
        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
        guiceBridge.bridgeGuiceInjector(GuiceContext.INJECTOR);
    }
}

이 등록할 수 있는 다른 기능이다.그 register 그것은 또는 검사에 대한 그것과 @Provider.

참고 ServiceLocatorProvider 만 사용할 수 있지 2.6 니다.

여기에는 솔루션입니다.

핵심은 무시 configureDeployment()메서드의 JerseyTest 을 만들 DeploymentContext 전달하여 특정 응용 프로그램 ResourceConfig.class 재정의하는 대로 구성()메소드를 반환하 ResourceConfig 인도록 컨테이너 테스트 초기화합니다 쥬스와 브리지 정확.

이것은 다음과 같은 버전의 저지,쥬스와 및 HK2 쥬스와 브리지

    <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)내 모의 서비스 Impl

public class MyMockServiceImpl implements MyService{
    public void hello() {
        System.out.println("Hi");
    }
} 

3)내 리소스 클래스와 쥬스와 주사 서비스

@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)나의 쥬스와 테스트 클래스 모듈

public class MyTestModule implements Module {

    @Override
    public void configure(Binder binder) {
            binder.bind(MyService.class)
               .to(MyMockServiceImpl.class);
    }

}

참고:나는 결코 사용되지기 전에.그러나,당신이하지 않아야 될 전화 new MyApp() 이제 더 이상그렇지 않으면 쥬스와 작동하지 않습니다.대신에,나도 이 같은 것:

public abstract class AbstractJerseyTest extends JerseyTest {
    private final Module[] modules;

    public AbstractJerseyTest(Module... modules) throws TestContainerException {
        super(new InMemoryTestContainerFactory());
        this.module = modules;
    }

    protected Application configure() {
        Injector inj = Guice.createInjector(modules);
        return inj.getInstance(MyApp.class);
    }
}

public class ActualTest extends AbstractJerseyTest {
    private static class TestModule extends AbstractModule {
        @Override
        public void configure() {
            // Do your guice bindings here
        }
    }

    public ActualTest() throws TestContainerException {
        super(new TestModule());
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top