Can't get JSON from http request
我实现了一个基于 Jersey 的 RESTful Web 服务。
发送请求时,我首先检查是否定义了一些强制参数,如果没有定义,则返回带有错误代码和错误消息的响应。
这是片段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @Path("/groups" ) @RequestScoped @Consumes( MediaType.APPLICATION_JSON ) @Produces( value = {MediaType.APPLICATION_JSON, MediaType.TEXT_XML} ) public class GroupResource { ... @POST public Response createGroup( Group group, @Context UriInfo uriInfo ) { logger.info("-------------------"); logger.info("Create group"); logger.fine(group.toString()); logger.info("-------------------"); // check mandatory fields if (!checkMandatoryFields(group, errorMessages)) { return Response.status(Status.BAD_REQUEST).entity(errorMessages).build(); } ... } |
然后我实现了一个 JUnit 测试来测试它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | @Test public void testCreateGroup() { try { URL url = new URL(URL_GROUPS_WS); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type","application/json"); String json2send ="{"grid":"1", "gidNumber":"2", "groupName":"TestGroup", "groupDescription":"Initial description", "targetSystems":["ADD TS1"]}"; OutputStream os = conn.getOutputStream(); os.write(json2send.getBytes()); os.flush(); System.out.println("XXXXXXXX Sending request XXXXXXXX \ "); if (conn.getResponseCode() != 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer error = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { error.append(inputLine); } in.close(); throw new RuntimeException("Failed : HTTP error code :" + conn.getResponseCode() + error.toString()); } ... } |
我的问题是我得到了
上面的代码,我检查响应代码的地方,不起作用...
你能帮帮我吗?
这不是正确测试球衣组件的方法,实际上您应该依赖
您当前的代码太容易出错,应该避免。
假设您使用
1 2 3 4 5 6 7 8 9 10 11 12 | <dependency> <groupId>org.glassfish.jersey.test-framework</groupId> jersey-test-framework-core</artifactId> <version>2.24</version> <scope>test</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.test-framework.providers</groupId> jersey-test-framework-provider-grizzly2</artifactId> <version>2.24</version> <scope>test</scope> </dependency> |
然后您可以简单地让您的单元测试扩展
你的测试类可能是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class GroupResourceTest extends JerseyTest { @Override protected Application configure() { return new ResourceConfig(GroupResource.class); } @Test public void testCreateGroup() { Group group = // create your group instance to test here Response response = target("/groups") .request() .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(group, MediaType.APPLICATION_JSON)); Assert.assertEquals(Response.Status.BAD_REQUEST, response.getStatus()); Assert.assertEquals("My error message", response.readEntity(String.class)); } } |
使用 ErrorStream 代替 InputStream -
1 |
ErrorStream 会在出现错误时给你响应。