spring - 使用Spring和Jersey测试框架进行单元测试

标签 spring unit-testing junit jersey

我正在使用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/

相关文章:

python - nosetest 弃用警告

java - 如何使用 JPA 和 JUnit 对不同的持久性单元进行测试?

java - 我的 JUnit 测试失败

java - 浏览器和 postman 返回结果,但 Resttemplate 由于 %26 返回 0 个结果

java - Spring数据排序操作超出最大大小

java - Servlet 调用失败。使用 Spring 支架

c++ - 私有(private)方法的单元测试

c# - 在单元测试中使用 httpcontext

java - JUnit Mockito 测试 : zero interactions

Java Spring hibernate HQL where 子句不起作用