[英]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.