首页 > 解决方案 > Jmeter,Groovy JSON slurper 用于作为变量的键

问题描述

我最近才读到 usingvars.get("variable")比 using 更有效${variable}。我有使用后者的经验,但它会导致错误,但我已经设法解决它,以便不再发生错误(我将不再讨论它,因为这不是我的问题)。这是代码的一部分:

import groovy.json.JsonSlurper;

String response = prev.getResponseDataAsString();

def jsonSlurper = new JsonSlurper();
def json = jsonSlurper.parseText(response);

if (json.data.target_list) {
    Random random = new Random();

    String[] strLeadDBIDList = json.data.target_list.keySet();
    int idxLeadDBID = random.nextInt(strLeadDBIDList.length);
    String strLeadDBID = strLeadDBIDList[idxLeadDBID];
    log.info("Leads Dashboard - Customer ID: " + strLeadDBID);
    vars.put("strLeadDBID",strLeadDBID);

    String strLeadDBModule = json.data.target_list."${strLeadDBID}".parent_type;
    log.info("Leads Dashboard - Customer Type: " + strLeadDBModule);
    vars.put("strLeadDBModule",strLeadDBModule);
...

所以我的问题是,有没有办法在代码中使用vars.get("strLeadDBID")而不是?或者我可以使用该变量,以及如何使用?谢谢!!!"${strLeadDBID}"String strLeadDBModule = json.data.target_list."${strLeadDBID}".parent_type;strLeadDBID

标签: jsongroovyjmeter

解决方案


我的期望是:

String strLeadDBModule = json.data.target_list.get(vars.get("strLeadDBID")).parent_type;

如果它不起作用,请执行以下操作:

log.info('Target list class name: ' + json.data.target_list.getClass().getName()))

并在jmeter.log文件中查找相关行。然后在Groovy GDK API 文档中检查给定类的 JavaDoc并寻找合适的函数。

同样根据JSR223 Sampler 文档

使用此功能时,请确保您的脚本代码不直接在脚本代码中使用 JMeter 变量,因为缓存只会缓存第一个替换。而是使用脚本参数

您可以尝试以下设置:

JMeter Groovy 参数

查看Apache Groovy - Why and How You Should Use It一文,了解有关在 JMeter 测试中使用 Groovy 脚本的更多提示


推荐阅读