How can I inject a data source dependency into a RESTful web service with Jersey (Test Framework)?

不问归期 提交于 2019-12-21 04:30:38

问题


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

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.

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.

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)?


回答1:


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

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();
}

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

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.



来源:https://stackoverflow.com/questions/5892349/how-can-i-inject-a-data-source-dependency-into-a-restful-web-service-with-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!