Accessing Spring beans in JerseyTest

2019-04-27 01:27发布

问题:

I'm trying to figure out how to access Spring beans from a subclass of JerseyTest. Extending JerseyTest I've managed to load the Spring context in my tests, but I haven't figured out how to access the spring context. My setup looks like this:

public abstract class SpringJerseyTest extends JerseyTest {
    public SpringJerseyTest() throws Exception {
        super(new WebAppDescriptor.Builder("com.acme.resources")
            .contextPath("/")
            .contextParam("contextConfigLocation", "classpath:applicationContext.xml")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .build());
    }

}

The setup is using the default Grizzly Web Container. I've never used Grizzly before, but in Jetty I would do something like this:

    public Object getSpringBean(String beanName) {
        WebAppContext context = (WebAppContext) server.getHandler();
        ServletContext sc = context.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
        return applicationContext.getBean(beanName);
    }

Could anyone point me in the right direction?

回答1:

I am using a naive approach but works

public ResourceIT()
    {
        super(new WebAppDescriptor.Builder("amazingpackage")
                .servletClass(SpringServlet.class)
                .contextParam("contextConfigLocation", "classpath:/spring/context.xml")
                .contextListenerClass(ContextLoaderListener.class)
                .contextPath("context")
                .build());
        injectedBean = ContextLoaderListener
                .getCurrentWebApplicationContext().getBean(InjectedBean.class);
    }


回答2:

Been using the solution described here for a week, and it's working fine.



回答3:

I dont understand the need of JerseyTest that uses Spring bean, often your Spring Beans are Service/Dao layer and they have to be Unit test / Integration Test on their layer, using Mockito or DBUnit (integration Tests).

I have been unit Testing Jersey Resource classes using Sprig beans as mocks, this is because you have to isolate the tests, and test only Jersey stuff (and Json) in JerseyTest, not Service or Dao Layer., Yes I do pass my spring bean context, but the spring beans are only mocks, cause I don't want to test the spring beans in JerseyTests.

If you isolate you tests it would be easier to write and maintain your tests