Question

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]

Was it helpful?

Solution

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top