我正在嘗試使用Jersey測試框架爲我的REST API編寫功能測試。然而,當我在功能測試中使用依賴注入時,我似乎遇到了障礙。我主要的應用程序是這樣的:Jersey測試,Grizzly和HK2依賴注入功能測試
@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服務定位與新澤西測試框架的方式還是我需要把我的應用程序作爲外部容器和使用外部容器供應商如下所述:External container?
此外,由於這些功能測試,嘲笑注入的服務不是一個選項。
爲什麼不能使用AbstractBinder將您的依賴項(接口與impl)綁定,然後將活頁夾註冊到ResourceConfig並將ResourceConfig傳遞給服務器? – Raf
@Raf這實際上是我最終走向的方向。我發現最好是明確聲明我的依賴關係,而不是掃描軟件包以找到它們。 –