如何使用Jersey(测试框架)将数据源依赖项注入到RESTful Web服务中? [英] How can I inject a data source dependency into a RESTful web service with Jersey (Test Framework)?

查看:87
本文介绍了如何使用Jersey(测试框架)将数据源依赖项注入到RESTful Web服务中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey来构建RESTful Web服务,该服务依赖于MongoDB的持久性.

I'm building a RESTful web service using Jersey that relies on MongoDB for persistence.

Web服务本身连接到默认数据库,但是对于单元测试,我想使用一个单独的测试数据库.我将在setUp中填充此测试数据库,运行测试,然后在tearDown中销毁它.

The web service itself connects to the default database, but for the unit tests, I would like to use a separate test database. I would populate this test database in setUp, run my tests, and then destroy it in tearDown.

通常,我将在此处使用依赖项注入将数据源提供给该服务将使用的实体管理器,但是在这种情况下,Web服务的运行独立于单元测试.我正在使用Jersey测试框架,该框架启动了一个Grizzly容器来提供Web服务接口,并为单元测试类提供Web Service客户端.

Normally, I would use dependency injection here to supply the data source to an entity manager that the service would use, but in this case the web service is running independent of the unit tests. I'm using the Jersey Test Framework, which starts up a Grizzly container to provide the web service interface, and provides a web service client to the unit testing class.

将来自单元测试类的依赖项注入服务器实例(该球衣测试框架在Grizzly容器中设置)的最佳方法是什么?

What is the best way to inject a dependency from my unit test class into the server instance (which Jersey Test Framework sets up in a Grizzly container)?

推荐答案

在浏览完Jersey测试框架的源代码之后,我发现了一种将依赖项注入到我的RESTful资源类中的优雅方法.

After digging through the Jersey Test Framework source, I've discovered an elegant way to inject dependencies into my RESTful resource classes.

在我的测试类(扩展了JerseyTest)中,我只为configure()方法添加了一个实现:

In my test class (which extends JerseyTest), I've added only an implementation for the configure() method:

public AppDescriptor configure() {
    return new WebAppDescriptor.Builder()
        .contextListenerClass(ContextLoaderListener.class)
        .contextParam("contextConfigLocation", "classpath:applicationContext.xml")
        .initParam("com.sun.jersey.config.property.packages", "[resource package]")
        .build();
}

这有效地提供了自定义构建的WebAppDescriptor,而不是依靠Jersey Test的Grizzly Web容器来构建一个.

This effectively provides a custom built WebAppDescriptor instead of relying on Jersey Test's Grizzly Web container to build one.

这将使用类路径上的"applicationContext.xml"文件,可以对该文件进行不同的配置以运行JUnit测试.实际上,我有两个不同的applicationContext.xml文件:一个用于JUnit测试,另一个用于生产代码. 测试的applicationContext.xml将以不同的方式配置数据访问依赖项对象.

This will use the "applicationContext.xml" file on the classpath, which can be configured differently for running JUnit tests. Effectively, I have two different applicationContext.xml files: one for my JUnit tests, and the other for production code. The test's applicationContext.xml will configure the data access dependency object differently.

这篇关于如何使用Jersey(测试框架)将数据源依赖项注入到RESTful Web服务中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆