简体   繁体   中英

Accessing Spring beans in JerseyTest

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?

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);
    }

使用这里描述的解决方案一周,它工作正常。

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

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