简体   繁体   中英

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM