Search code examples
groovyjmeterblazemeter

Save a variable inside groovy in JMeter


I have a loop controller in which I'm generating a random number for the loop count using groovy. (the below image)

enter image description here

Is there anyway I can save this "val" variable in this groovy command (I don't want to use a sampler)?

I tried vars.putObject("val", val) and vars.put("val", val.toString()) but they don't work. (the loop does not work at all, so I assume groovy does not understand vars.put?)


Solution

  • If something "doesn't work" first of all check jmeter.log file.

    Groovy "understands" vars.put however there is a nuance: if you have a comma inside a JMeter Function you need to escape it with a backslash so you need to do something like:

    vars.putObject('val'\, val)
    

    full function just in case:

    ${__groovy(val = (int) Math.round(new Random().nextGaussian() * 0.11 + 0.01); val = val < 0 ? 0 : val; vars.putObject('val'\, val),)}
    

    More information: Apache JMeter Functions - An Introduction