0
votes

I'm preparing data to be sent as part of HTTP request, so the data preparation part is being done in BeanShell preprocessor.

As the request size changes, I need a variable length of JSON to be passed. I am creating JSON body in for loop, but the parameters are not changing, Ex:

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})} remains same inside the loop.

How to enable the change inside loop?

2

2 Answers

1
votes

In scrips use props instead function and vars instead of variable

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

Why do you expect it to change? JMeter Properties are global for the whole JVM and shared across all threads. Therefore ${__P(marks${line_offset})} will always have the same value unless you set it somewhere else. As per documentation:

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

Few more things to check/fix:

  1. In general your script will not work in its current state as it is full of errors, like:

    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.
    

    Next time you will face the problem please provide exact code

  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. As per JSR223 Sampler documentation - presumably the main cause of your problem:

    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");