【问题标题】:How to compare json responses?如何比较json响应?
【发布时间】:2019-08-23 08:27:28
【问题描述】:

我需要比较 beanshell 采样器中的 json 响应并打印条件是否通过。有人可以帮忙吗,我们如何比较它? 我已经有一个 json 格式的响应,一个我会在测试执行时得到另一个,我需要比较这两个单词。

 I tried using if/else but then its not working properly.


JSONObject JsonResponseinput = new JSONObject();
JsonResponseinput.toString();

print(JsonResponseinput +  " = PASS");
    f.close();

String s=JsonResponseinput.toString();

if (s == JsonResponse)
{
    f = new FileOutputStream("output/path/API_OUTPUT.csv", true);
     p = new PrintStream(f);
     this.interpreter.setOut(p);
    print(s +  " = PASS");
    f.close();
}
Else
{
    print(JsonResponseinput +  " = FAIL")

}

【问题讨论】:

  • JsonResponse 是什么?

标签: json jmeter beanshell


【解决方案1】:

至少有 4 种方法可以做到这一点:

  1. 使用Jackson 喜欢:

    final JSONObject obj1 = /*json*/;
    final JSONObject obj2 = /*json*/;
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode tree1 = mapper.readTree(obj1.toString());
    final JsonNode tree2 = mapper.readTree(obj2.toString());
    if (tree1.equals(tree2)) {
         log.info('PASS');
    }
    else {
         log.info('FAIL')
    }
    
  2. 使用GSON 喜欢:

    JsonParser parser = new JsonParser();
    JsonElement o1 = parser.parse("{a : {a : 2}, b : 2}");
    JsonElement o2 = parser.parse("{b : 2, a : {a : 2}}");
    assertEquals(o1, o2); 
    
  3. 使用JsonSlurper 喜欢:

    def json1 = new groovy.json.JsonSlurper().parseText("json1")
    def json2 = new groovy.json.JsonSlurper().parseText("json2")
    
    if (json1 == json2) {
        log.info('PASS')
    } else {
        log.info('FAIL')
    }
    
  4. 使用JSONAssert点赞

    try {
        org.skyscreamer.jsonassert.JSONAssert.assertEquals("json1", "json2", false)
        println('PASS')
    }
    catch (Exception ex) {
        println('FAIL')
    }
    

更多信息:The Easiest Way To Compare REST API Responses Using JMeter

附:忘记 Beanshell,since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language 用于任何形式的脚本

【讨论】:

    【解决方案2】:

    您可以使用以下方式比较 2 个 JSON 响应:

    1. 使用 JSON 提取器提取两个 JSON 响应 [提取完整响应]
    2. 使用JSR223 Sampler处理Script区的代码

      String response1 = vars.get("jsonOutput1");
      String response2 = vars.get("jsonOutput2");
      
      if (response1.equals(response2)) {
      log.info("Responses are equal");
      }
      else {
          log.info("Responses are not equal");
      }
      

    【讨论】:

      【解决方案3】:

      我使用来自 DeltaXML 的名为 DeltaJSON 的工具进行 JSON 比较,有一个简洁的 GUI 和 REST 界面。您可以使用 REST API 并解析响应。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-21
        • 1970-01-01
        • 2020-03-24
        • 2018-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-24
        相关资源
        最近更新 更多