How to make Jersey Unit test for Post method

10,149
@Path("hello")
public static class HelloResource {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String doPost(Map<String, String> data) {
        return "Hello " + data.get("name") + "!";
    }

}

@Override
protected Application configure() {
    return new ResourceConfig(HelloResource.class);
}

@Test
public void testPost() {
    Map<String, String> data = new HashMap<String, String>();
    data.put("name", "popovitsj");

    final String hello = target("hello")
            .request()
            .post(Entity.json(data), String.class);

    assertEquals("Hello popovitsj!", hello);
}
Share:
10,149
wvdz
Author by

wvdz

Frontend engineer at AWS.

Updated on June 26, 2022

Comments

  • wvdz
    wvdz almost 2 years

    Questions

    How do create a Jersey Unit Test for a POST?

    How do I add post parameters?

    What I tried

    For a GET it is easy (https://jersey.java.net/documentation/latest/test-framework.html):

        @Test
        public void test() {
            final String hello = target("hello").request().get(String.class);
            assertEquals("Hello World!", hello);
        }
    

    For a post it is more diffuse. I managed to get the response object, but how do I get the actual response object (the String)?

    @Test
    public void test() {
        Response r = target("hello").request().post(Entity.json("test"));
        System.out.println(r.toString());
    }
    

    Result: InboundJaxrsResponse{context=ClientResponse{method=POST, uri=http://localhost:9998/hello, status=200, reason=OK}}