如何为POST创建Jersey单元测试?
如何添加发布参数?
对于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);
}
对于帖子,它更分散。我设法获得了响应对象,但是如何获得实际的响应对象(字符串)?
@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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句