Unit testing Apache Wink REST service with MockServletInvocationTest

十年热恋 提交于 2019-12-08 13:09:03

问题


I use Apache Wink 1.2.1. I would like to unit test my REST service, and I'd rather doing it without using a RestClient. I haven't found any example, but after a lot of searching around I guessed that MockServletInvocationTest was the right starting point ... however I have not been able to make it work.

Here is a minimal example that fails for me.

My REST service:

@Path("greetings")
public class GreetingsResource {

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

}

The corresponding unit test:

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

}

So, I have a couple of questions:

  1. Am I going in the wrong direction?

  2. If I'm going in the right direction, then what am I doing wrong? When executing the previous test case I get the following error (which I really don't understand):

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


回答1:


I found what my problem was, and I just leave a note here in case someone had the same problem.

Here is why I got the NoSuchMethodError:

  • I use Apache Maven to handle dependencies
  • to use MockHttpServletRequest and MockHttpServletResponse I included a dependency to spring-mock 2.0.8:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-mock</artifactId>
      <version>2.0.8</version>
      <scope>test</scope>
    </dependency>
    
  • unfortunately spring-mock 2.0.8 has a dependency to commons-logging 1.1, which, in turn, has a dependency to servlet-api 2.3, in which javax/servlet/http/HttpServletResponse.getContentType()Ljava/lang/String does not exists! That method exists since servlet-api 2.4

So, to solve my problem I simply added an explicit dependency to servlet-api 2.4 with scope test! Now my unit test works without a problem!



来源:https://stackoverflow.com/questions/15203197/unit-testing-apache-wink-rest-service-with-mockservletinvocationtest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!