【问题标题】:How can I pass JSON response from http request to jsr223 assertion using groovy in Jmeter?如何使用 Jmeter 中的 groovy 将来自 http 请求的 JSON 响应传递给 jsr223 断言?
【发布时间】:2019-11-02 10:41:44
【问题描述】:

我有一个返回以下结果的 API:

{"success":true,
  "error":null,
  "data": {"EmpId":444,"ProfileNo":0,"ProfileName":"xya","Rank":0,"ScoreValue":0,"CompanyEmpID":"A25842"}}

我需要将上面的 JSON 传递给 JSR223 断言以单独验证所有输出值。我设法编写了以下脚本

import groovy.json.JsonSlurper;
JsonSlurper JSON = new JsonSlurper ();

def expected = new groovy.json.JsonSlurper().parseText(vars.get('Employee 
data'))
def actual = new 
groovy.json.JsonSlurper().parse(prev.getResponseData({"success":true,
"error":null,
"data":

{"EmpId":444,
 "ProfileNo":0,
 "ProfileName":"xya","Rank":0,"ScoreValue":0,"CompanyEmpID":"A25842"}})

 if (expected != actual) {
 AssertionResult.setFailure(true)
 AssertionResult.setFailureMessage('Mismatch between expected and actual 
 JSON')
  }

但它失败了。我收到如下错误:

断言错误:真 断言失败:假 断言失败消息:javax.script.ScriptException:org.codehaus.groovy.control.MultipleCompilationErrorsException:启动失败: Script20.groovy: 10: 期待 '}',在第 10 行第 81 列找到':'。 rev.getResponseData({"成功":true, ^

1 个错误

【问题讨论】:

    标签: json groovy jmeter


    【解决方案1】:

    正确的代码应该是这样的:

    def expected = new groovy.json.JsonSlurper().parseText('{"success":true,\n' +
            '  "error":null,\n' +
            '  "data": {"EmpId":444,"ProfileNo":0,"ProfileName":"xya","Rank":0,"ScoreValue":0,"CompanyEmpID":"A25842"}}')
    
    def actual = new groovy.json.JsonSlurper().parse(prev.getResponseData())
    
    if (expected != actual) {
        AssertionResult.setFailure(true)
        AssertionResult.setFailureMessage('Mismatch between expected and actual JSON ')
    }
    

    但是,它仅适用于第一级值,如果您将使用该方法来比较嵌套的 JSON 对象 - 您将得到误报结果,因此最好使用 JacksonJSONAssert 库执行“深度扫描”,查看The Easiest Way To Compare REST API Responses Using JMeter 文章了解更多详情。

    【讨论】:

    • 非常感谢@dmitri-t 它对我有用!!我想知道是否要将预期结果写入 excel 文件并可以将其与相同的 Json(我的 API 调用的输出)进行比较,我该怎么做?
    【解决方案2】:

    您可以使用json断言来验证值,如下所示;-

    带有响应的 JSON 请求(使用虚拟 Samlper)

    放置断言路径和期望值。 下面我有更改值以查看它是否有效,如果值更改则失败。否则它按预期工作。

    希望这会有所帮助。 这和 JSR223 无关,而是使用 json 断言。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多