如何为 Post 方法进行 Jersey 单元测试
How to make Jersey Unit test for Post method
问题
如何为 POST 创建 Jersey 单元测试?
如何添加 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);
}
对于 post 它更分散。我设法获得了响应对象,但如何获得实际的响应对象(字符串)?
@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}}
@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);
}
问题
如何为 POST 创建 Jersey 单元测试?
如何添加 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);
}
对于 post 它更分散。我设法获得了响应对象,但如何获得实际的响应对象(字符串)?
@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}}
@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);
}