我正在尝试使用 Jersey 测试框架为我的 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 测试框架为我的应用程序创建功能测试?
我的单元测试目前看起来像这样:
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 测试框架一起使用,或者我是否需要将我的应用程序视为外部容器并使用此处记录的外部容器提供程序:外部容器?
此外,由于这些是功能测试,因此在这里模拟注入的服务不是一个选项。