Unit testing with Spring and the Jersey Test Framework

18,313

Solution 1

I found a couple of ways to resolve this problem.

First up, over at the geek@riffpie blog there is an excellent description of this problem along with an elegant extension of JerseyTest to solve it: Unit-testing RESTful Jersey services glued together with Spring

Unfortunately, I'm using a newer version of Spring and/or Jersey (forget which) and couldn't quite get it to work.

In my case, I ended up avoiding the problem by dropping the Jersey Test Framework and using embedded Jetty along with the Jersey Client. This actually made better sense in my situation anyway since I was already using embedded Jetty in my application. yves amsellem has a nice example of unit testing with the Jersey Client and embedded Jetty. For Spring integration, I used a variation of Trimbo's Jersey Tests with Embedded Jetty and Spring

Solution 2

Override JerseyTest.configure like so:

@Override
protected Application configure() {
  ResourceConfig rc = new JerseyConfig();

  rc.register(SpringLifecycleListener.class);
  rc.register(RequestContextFilter.class);

  rc.property("contextConfigLocation", "classpath:helloContext.xml");
  return rc;
}

For me the SpringServlet was not required, but if you need that you may be able to call rc.register for that too.

Share:
18,313

Related videos on Youtube

HolySamosa
Author by

HolySamosa

Updated on June 04, 2022

Comments

  • HolySamosa
    HolySamosa almost 2 years

    I'm writing some JUnit-based integration tests for a RESTful web service using JerseyTest. The JAX-RS resource classes use Spring and I'm currently wiring everything together with a test case like the following code example:

    public class HelloResourceTest extends JerseyTest
    {
        @Override
        protected AppDescriptor configure()
        {
            return  new WebAppDescriptor.Builder("com.helloworld")
            .contextParam( "contextConfigLocation", "classpath:helloContext.xml")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .requestListenerClass(RequestContextListener.class)
            .build();        
        }
    
        @Test
        public void test()
        {
            // test goes here
        }
    }
    

    This works for wiring the servlet, however, I'd like to be able to share the same context in my test case so that my tests can have access to mock objects, DAOs, etc., which seems to call for SpringJUnit4ClassRunner. Unfortunately, SpringJUnit4ClassRunner creates a separate, parallel application context.

    So, anyone know how can I create an application context that is shared between the SpringServlet and my test case?

    Thanks!

  • yves amsellem
    yves amsellem almost 12 years
    This other sample code allows to chose between Grizzly or Jetty for deployment. Grizzly is a little bit faster, but can't use web.xml (so it has to be configured by code).