如何对Post方法进行Jersey Unit测试

时间:2015-06-17 14:40:06

标签: java rest junit jersey jax-rs

问题

如何为POST创建泽西岛单元测试?

如何添加帖子参数?

我尝试了什么

对于GET来说,这很简单(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);
    }

对于帖子来说,它更加分散。我设法得到了响应对象,但是如何获得实际的响应对象(String)?

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

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

1 个答案:

答案 0 :(得分:7)

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