HTTPBuilder GET的JSON格式结果在0.5.2和0.6之间变化

Rob*_*ert 1 groovy json httpbuilder jsonassert

我们最近更新了REST集成测试的依赖项,该测试使用了Groovy,HTTPBuilder,JSONAssert和Junit.当我们从HTTPBuilder 0.5.2到0.6时,我们的许多测试都失败了.

我们发现由于HTTPBuilder中的一个新"功能"提供了"对已注册内容类型的自动响应解析",响应格式发生了变化.

旧的,(0.5.2)格式,预期响应:

[ { "name":"Portfolio_REST_Test01", "description":"", "referenceValueType":"Net Value", "unitType":"SHARES", "tags":[] } ]

新的(0.6.2)响应格式:

[{tags=[], referenceValueType=Net Value, unitType=SHARES, description=, name=Portfolio_REST_Test01}]
Run Code Online (Sandbox Code Playgroud)

当JSONAssert尝试解析值为空字符串的命名值时,会出现问题,请参阅上面示例中的"描述".JSONAssert期望一个字符遵循等号而不是逗号,并在遇到时抛出异常.

Rob*_*ert 7

进一步深入研究,我们发现必须对HTTPBuilder进行更改才能继续获得0.5.2提供的无格式响应.

旧的Groovy代码剪辑:

  // perform a GET request, expecting JSON response data
  http.request(Method.GET, ContentType.JSON) { req ->

     uri.path = restPath;
     requestContentType = JSON;
     uri.query = mapQuery;
     headers.Accept = 'application/json';

     // response handler for a successful response code:
     response.success = { resp, json ->
   // Check returned status'
   assertResp(resp, expStatus);
   return json.toString();
     }
     // Check returned status' for the 400's and 500's
     response.failure = { resp ->
        // Check returned status'
        assertResp(resp, expStatus);
     }
Run Code Online (Sandbox Code Playgroud)

HTTPBuilder文档表明自动格式化将用于已知类型,如JSON和XML.要关闭此功能,必须在http.request中指定TEXT的ContentType.但是当这样做时,"json"对象的toString值(在response.success闭包内)不再返回返回的JSON值.这些值可在"text"属性中找到.

所以最终的代码如下所示:

  // perform a GET request, expecting JSON response data
  http.request(Method.GET, ContentType.TEXT) { req ->

     uri.path = restPath;
     requestContentType = JSON;
     uri.query = mapQuery;
     headers.Accept = 'application/json';

     // response handler for a successful response code:
     response.success = { resp, json ->
   // Check returned status'
   assertResp(resp, expStatus);
   return json.text;
     }
     // Check returned status' for the 400's and 500's
     response.failure = { resp ->
        // Check returned status'
        assertResp(resp, expStatus);
     }
Run Code Online (Sandbox Code Playgroud)

希望如果有人遇到同样的问题,他们会咨询Stack Overflow,他们会发现这些笔记很有帮助.最好的祝福