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 |
然后我实现了一个 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(); String json2send =“{“grid“:”1“, “gidNumber“:”2“, “groupName“:”TestGroup“, “groupDescription“:”Initial description“, “targetSystems“:[“ADD TS1“]}”; OutputStream os = conn.getOutputStream(); System.out.println(“XXXXXXXX Sending request XXXXXXXX \ if (conn.getResponseCode() != 200) StringBuffer error = new StringBuffer(); in.close(); throw new RuntimeException(“Failed : HTTP error code :” + conn.getResponseCode() + error.toString()); |
我的问题是我得到了 responseCode,但我不知道如何得到错误消息,它应该在响应中的某个地方,对吧? (Response.status(Status.BAD_REQUEST).entity(**errorMessages**).build()).
上面的代码,我检查响应代码的地方,不起作用…
你能帮帮我吗?
- 精确定义”不起作用”。你期望会发生什么,但会发生什么?
这不是正确测试球衣组件的方法,实际上您应该依赖 Jersey Test Framework 来测试组件,因为它隐藏了很多复杂性,因此您的单元测试易于阅读和维护。
您当前的代码太容易出错,应该避免。
假设您使用 maven,您需要将接下来的 2 个依赖项添加到具有 test 范围的项目中。
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> |
然后您可以简单地让您的单元测试扩展 JerseyTest 并覆盖方法 configure 以提供您的其余组件的类,并为环境设置完成。它会自动启动一个 grizzly 服务器并为你绑定你的组件,所以剩下要做的就是编写你的单元测试。
你的测试类可能是这样的:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class GroupResourceTest extends JerseyTest {
@Override @Test |
使用 ErrorStream 代替 InputStream –
1
|
ErrorStream 会在出现错误时给你响应。
来源:https://www.codenong.com/40719648/