繁体   English   中英

访问JerseyTest中的Spring bean

[英]Accessing Spring beans in JerseyTest

我试图弄清楚如何从JerseyTest的子类访问Spring bean。 扩展JerseyTest我已经设法在我的测试中加载Spring上下文,但我还没弄清楚如何访问spring上下文。 我的设置如下:

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

}

该设置使用默认的Grizzly Web容器。 我之前从未使用Grizzly,但在Jetty中我会做这样的事情:

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

有人能指出我正确的方向吗?

我正在使用一种天真的方法,但有效

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

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

我不明白使用Spring bean的JerseyTest的需要,通常你的Spring Beans是Service / Dao层,他们必须在他们的层上进行单元测试/集成测试,使用Mockito或DBUnit(集成测试)。

我一直在使用Sprig bean作为模拟单元测试Jersey资源类,这是因为你必须隔离测试,并且只测试JerseyTest中的Jersey东西(和Json),而不是Service或Dao Layer。是的,我确实通过了我的spring bean上下文,但春豆只是嘲笑,因为我不想测试JerseyTests中的春豆。

如果您隔离测试,则编写和维护测试会更容易

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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