簡體   English   中英

使用Jersey Test,Grizzly和HK2依賴注射進行功能測試

[英]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框架一起使用,或者我是否需要將我的應用程序視為外部容器並使用外部容器提供程序,如下所示: 外部容器

此外,由於這些是功能測試,因此模擬注入的服務不是一種選擇。

您可以使用定位器橋來獲取兩個單獨的定位器(您創建的定位器和來自Jersey的定位器)並將它們連接在一起。 橋也可以是雙向的(在限制范圍內),因此它在大多數正常使用中都會出現一個大的ServiceLocator。

請注意,本周修復了ServiceLocator橋的一個錯誤,該橋尚未被推送到maven但是(可能)將在下周的某個時間推送。 HK2-295

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM