Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with Spring and the Jersey Test Framework

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!

like image 941
HolySamosa Avatar asked May 15 '12 19:05

HolySamosa


2 Answers

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.

like image 128
Ben Page Avatar answered Sep 20 '22 19:09

Ben Page


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

like image 30
HolySamosa Avatar answered Sep 16 '22 19:09

HolySamosa