我正在尝试使用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这实际上是我最终走向的方向。我发现最好是明确声明我的依赖关系,而不是扫描软件包以找到它们。 –