Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 858
Tharsan Avatar asked May 05 '11 03:05

Tharsan


1 Answers

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.

like image 176
Tharsan Avatar answered Oct 20 '22 23:10

Tharsan