我正在使用JerseyTest为RESTful Web服务编写一些基于JUnit的集成测试。 JAX-RS资源类使用Spring,我目前正在将所有内容与一个测试用例连接在一起,例如以下代码示例:
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和测试用例之间共享的应用程序上下文吗?
谢谢!
最佳答案
像这样覆盖JerseyTest.configure:
@Override
protected Application configure() {
ResourceConfig rc = new JerseyConfig();
rc.register(SpringLifecycleListener.class);
rc.register(RequestContextFilter.class);
rc.property("contextConfigLocation", "classpath:helloContext.xml");
return rc;
}
对我来说,SpringServlet不是必需的,但是如果您需要,您也可以为此调用rc.register。
关于spring - 使用Spring和Jersey测试框架进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607168/