2016-07-14 127 views
1

我正在嘗試使用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

此外,由於這些功能測試,嘲笑注入的服務不是一個選項。

+0

爲什麼不能使用AbstractBinder將您的依賴項(接口與impl)綁定,然後將活頁夾註冊到ResourceConfig並將ResourceConfig傳遞給服務器? – Raf

+0

@Raf這實際上是我最終走向的方向。我發現最好是明確聲明我的依賴關係,而不是掃描軟件包以找到它們。 –

回答

0

您可以使用Locator Bridge取兩個單獨的定位符(您創建的定位符和來自澤西島的定位符)並將它們橋接在一起。該橋也可以是雙向的(在限制範圍內),因此它會以最常用的形式出現在一個大的ServiceLocator中。

請注意,本週有一個錯誤修復了ServiceLocator網橋,該網橋尚未推送給maven,但將於下週某個時間推出。請參閱HK2-295