[英]jersey + grizzly + hk2: Dependency injection, but not into resource
[英]Functional tests with Jersey Test, Grizzly and HK2 Dependency Injection
我正在尝试使用Jersey Test框架为我的REST API编写功能测试。 但是,在我的功能测试中使用依赖注入时,我似乎遇到了障碍。 我的主要应用程序如下所示:
@ApplicationPath("/")
public class Application extends ResourceConfig {
private static final URI BASE_URI = URI.create("http://localhost:8080/api/");
public static void main(String[] args) throws Exception {
System.out.println("Starting application...");
final ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
final ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(JacksonFeature.class);
resourceConfig.register(LoggingFeature.class);
resourceConfig.packages(true, "my.package.name");
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig, locator);
Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow));
server.start();
Thread.currentThread().join();
}
}
请注意,我正在使用HK2的ServiceLocatorUtilities.createAndPopulateServiceLocator()
方法来读取hk2-metadata-generator
文件。 此方法创建一个ServiceLocator
对象,然后将该对象传递给GrizzlyHttpServerFactory.createHttpServer
方法。 这对于运行Grizzly服务器非常有用,但是,我现在的问题是如何使用Jersey Test Framework为我的应用程序创建功能测试?
我的单元测试目前看起来像这样:
public class FormsResourceTest extends JerseyTest {
@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
@Test
public void testMe() {
Response response = target("/test").request().get();
assertEquals("Should return status 200", 200, response.getStatus());
}
}
有没有办法将HK2服务定位器与Jersey Test框架一起使用,或者我是否需要将我的应用程序视为外部容器并使用外部容器提供程序,如下所示: 外部容器 ?
此外,由于这些是功能测试,因此模拟注入的服务不是一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.