Unit Testing Spring Jersey Integration
Recently, I’ve been working on a side project which has given me the opportunity to play with an interesting Java technology stack. After a few weekends of working on the build and moving my way up the stack from database to service layer I was at the point of writing a full integration test. In the past I’ve done integration testing with an iBatis/Spring stack, which, with the help of DBUnit is a fairly simple exercise. However, this project is heavily REST based and the addition of Jersey (JAX-RS) was a serious curveball.
To really test the whole stack an embedded webserver is required. Looking through the Jersey/Spring unit tests they make use of an exploded WAR using Glassfish. Assuming this was the optimal solution I added Glassfish to my ivy.xml config and ran an ivy update. However, once I realized the overwhelming volume of jars being downloaded I decided it was much too heavy weight of a solution.
My next choice was Jetty. I have had experience with using Jetty in the past but I quickly ran into issues trying to get it working right with Jersey, Spring, and an exploded WAR configuration. It was then that I saw the GrizzlyServerFactory referenced in another Jersey unit test. After some prodding and reading into the source code I ended up with the following:
final URI baseUri = UriBuilder.fromUri( "http://localhost/" ).port( 9998 ).build(); final ServletAdapter adapter = new ServletAdapter(); adapter.addInitParameter( "com.sun.jersey.config.property.packages", <your-package-name> ); adapter.addContextParameter( "contextConfigLocation","classpath:applicationContext.xml" ); adapter.addServletListener( "org.springframework.web.context.ContextLoaderListener" ); adapter.setServletInstance( new SpringServlet() ); adapter.setContextPath( baseUri.getPath() ); SelectorThread threadSelector = GrizzlyServerFactory.create( baseUri, adapter );
We start by making a base Uri for localhost at a high numbered port. Then we build the Grizzly ServletAdaptor. The first parameter is the package name where your Jersey enabled are located. The next two lines are taken directly from the web.xml file that is used for the actual WAR. The first is the config location for the Spring Context and the second is the ContextLoaderListener servlet. Finally we add the Jersey SpringServlet and the context path. With these two objects created we can build a SelectorThread and begin using the server using the Jersey Client api that I talked about in my previous post. When you are done, don’t forget to call stopEndpoint() on the SelectorThread when you are done.
Tags: Grizzly, JAX-RS, Jersey, REST, Spring, unit test
You can comment below, or link to this permanent URL from your own site.