【问题标题】:Unit testing Apache Wink REST service with MockServletInvocationTest使用 MockServletInvocationTest 对 Apache Wink REST 服务进行单元测试
【发布时间】:2013-10-16 19:30:57
【问题描述】:

我使用 Apache Wink 1.2.1。我想对我的 REST 服务进行单元测试,并且我宁愿不使用RestClient 进行测试。我没有找到任何示例,但是经过大量搜索后,我猜想MockServletInvocationTest 是正确的起点……但是我无法使其工作。

这是一个对我来说失败的最小示例。

我的 REST 服务:

@Path("greetings")
public class GreetingsResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello World!";
    }

}

对应的单元测试:

public class GreetingsResourceTest extends MockServletInvocationTest {

    @Override
    protected Class<?>[] getClasses() {
        return new Class<?>[] { GreetingsResource.class };
    }


    public void testHello() throws ServletException, IOException {
        MockHttpServletRequest request = MockRequestConstructor.
            constructMockRequest("GET", "/greetings", MediaType.TEXT_PLAIN);
        MockHttpServletResponse response = invoke(request);
        assertEquals(200, response.getStatus());
    }

}

所以,我有几个问题:

  1. 我是不是走错方向了?

  2. 如果我朝着正确的方向前进,那么我做错了什么?执行上一个测试用例时出现以下错误(我真的不明白):

java.lang.NoSuchMethodError: javax/servlet/http/HttpServletResponse.getContentType()Ljava/lang/String; 在 org.apache.wink.server.internal.handlers.FlushResultHandler$FlushHeadersOutputStream.flushHeaders(FlushResultHandler.java:350) ~[wink-server-1.2.1-incubating.jar:1.2.1-incubating]

【问题讨论】:

    标签: junit mocking apache-wink


    【解决方案1】:

    我发现了我的问题,我只是在这里留下一个便条,以防有人遇到同样的问题。

    这就是我得到NoSuchMethodError的原因:

    • 我使用Apache Maven 来处理依赖关系
    • 为了使用 MockHttpServletRequestMockHttpServletResponse,我包含了对 spring-mock 2.0.8 的依赖:

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-mock</artifactId>
        <version>2.0.8</version>
        <scope>test</scope>
      </dependency>
      
    • 不幸的是 spring-mock 2.0.8 依赖于 commons-logging 1.1,而后者又依赖于 servlet-api 2.3,其中 javax/servlet/http/HttpServletResponse.getContentType()Ljava/lang/String 不存在!该方法从 servlet-api 2.4 开始就存在

    所以,为了解决我的问题,我只是在 servlet-api 2.4 中添加了一个显式依赖项,并使用范围测试!现在我的单元测试没有问题了!

    【讨论】:

    • 你是如何发现依赖错误的? maven tree ?
    • @bubuzzz:老实说,我不记得我是怎么想出来的 :) ...我猜是因为我绝望了,我开始遍历所有 Maven 依赖树。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2018-11-09
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    相关资源
    最近更新 更多