JMeter中同一个请求每次出现更新参数值

Update the parameter value for each occurrence for the same request in JMeter

我正在准备要作为 HTTP 请求的一部分发送的数据, 所以数据准备部分是在 BeanShell 预处理器中完成的。

随着请求大小的变化,我需要传递JSON的可变长度。 我在 for 循环中创建 JSON 主体,但参数没有改变,例如:

try{
    int[] po = {20, 30, 40, 50, 75};
    int rNum = getRandom(0,4);

    String name="${name}";
    String _class="${_class}";
    StringBuilder msgBody = new StringBuilder();
    msgBody.append("{\"name\":\"")
    .append(name)
    .append("\", \"class\":\"")
    .append(_class)
    .append("\", \"marks\":[");
    for (int i=0;i<po\"[rNum];i++)
    {   
        msgBody.append("{ \"subject\":\"${__P(marks${line_offset})}\"," },");
     }
     int length=msgBody.length()-1;
     log.info(String.valueOf(length));
    msgBody.setLength(length);
    msgBody.append("] }");
    vars.put("json",msgBody.toString());
}

${__P(marks${line_offset})} 在循环中保持不变。

如何启用循环内的更改?

在脚本中使用 props 代替函数,使用 vars 代替变量

  props.get("marks" + vars.get("line_offset"));

您为什么期望它发生变化? JMeter 属性对于整个 JVM 是 global 并且在所有线程之间共享。因此 ${__P(marks${line_offset})} 将始终具有相同的值,除非您将其设置在其他地方。根据 documentation:

Properties are not the same as variables. Variables are local to a thread; properties are common to all threads

还有一些事情要 check/fix:

  1. 一般来说,您的脚本在当前状态下无法运行,因为它充满了错误,例如:

    int[] po\" = {20, 30, 40, 50, 75}; // won't compile due to \"
    String class="${class}"; // won't compile as "class" is a reserved keyword
    etc.
    

    下次遇到问题请提供准确代码

  2. Since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language for scripting mainly because Groovy performance is much better comparing to Beanshell. Particular in your case you can have benefit from using JsonBuilder and/or JsonOutput

  3. 根据 JSR223 Sampler 文档 - 可能是您问题的主要原因:

    JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g.

    props.get("START.HMS");

    props.put("PROP1","1234");