2012-05-15 139 views
8

我正在为使用JerseyTest的REST风格的Web服务编写一些基于JUnit的集成测试。在JAX-RS资源类使用Spring和我目前正在与一个测试用例状引线evernthing一起以下:使用Spring和Jersey测试框架进行单元测试

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

这适用于布线servlet的,但是,我希望能够分享在我的测试用例中使用相同的上下文,以便我的测试可以访问模拟对象,DAO等,这似乎要求SpringJUnit4ClassRunner。不幸的是,SpringJUnit4ClassRunner创建了一个单独的并行应用程序上下文。

因此,任何人都知道如何创建一个在SpringServlet和我的测试用例之间共享的应用程序上下文?

谢谢!

回答

5

我找到了几种方法来解决这个问题。

首先亮相,在在怪胎@ riffpie博客出现这个问题的一个很好的描述与JerseyTest优雅的延长而解决这个问题: Unit-testing RESTful Jersey services glued together with Spring

不幸的是,我使用的是较新版本春天和/或泽西(忘记),并不能完全实现它的工作。

在我的情况下,我最终通过删除Jersey测试框架并使用嵌入式Jetty和Jersey客户端来避免该问题。这实际上在我的情况下更好理解,因为我已经在我的应用程序中使用了嵌入式Jetty。 yves amsellem有一个很好的例子unit testing with the Jersey Client and embedded Jetty。对于Spring集成,我用Trimbo的Jersey Tests with Embedded Jetty and Spring

+0

[此其他示例代码](https://github.com/yamsellem/jersey-basics/blob/master/src/test/java/com/xebia/resource/ProductResourceJacksonTest.java)允许选择灰熊或Jetty进行部署。 Grizzly速度稍快一些,但不能使用web.xml(因此它必须由代码配置)。 –

9

覆盖JerseyTest.configure的像这样的变化:对我来说是不需要SpringServlet

@Override 
protected Application configure() { 
    ResourceConfig rc = new JerseyConfig(); 

    rc.register(SpringLifecycleListener.class); 
    rc.register(RequestContextFilter.class); 

    rc.property("contextConfigLocation", "classpath:helloContext.xml"); 
    return rc; 
} 

,但是如果你需要,你可能能够调用rc.register也是如此。

+1

您的解决方案适用于Jersey 2.x. – NSPKUWCExi2pr8wVoGNk

+0

@ben:请帮我将多个应用程序上下文传递给contextConfigLocation?逗号分隔或字符串数​​组在这里是不允许的。 – developer

+0

一种方法是创建测试弹簧上下文并在文件中导入您的应用程序上下文。使用泽西配置中的测试文件 – Chandru

相关问题