Search code examples
groovyjmeterjsr223

Jmeter - Loop through the array defined from 'User Defined Variables'


I try to Loop scenario for 2 times fetching data from array.

My use case is: I want to create user, for multiple countries, so instead of coping the case, I want to implement loop logic.

So far a tried like, but without success:

  1. from here I want to fetch data

//JSR223 PreProcessor

String[] varArray = {"US", "UK"};
idx = Integer.parseInt(vars.get("loopCounter"))-1;
vars.put("myVariable", varArray[idx]);

enter image description here

  1. counter logic: enter image description here

  2. Whole script, which is chain of multiple API calls, and i want to use fetch data, only a single call.

enter image description here

Result: I got null, if I try to use fetch variable.

Script37.groovy: 1: unexpected token: US @ line 1, column 22.
   String[] varArray = {"US", "UK"};

Solution

    1. Define countries variable via User Defined Variables like:

      enter image description here

    2. In the Loop Controller you can dynamically get the array length via __groovy() function as:

      ${__groovy(vars.get('countries').split().size(),)}
      

      enter image description here

    3. Wherever you want inside the Loop Controller you can reference the "current" country for the given loop as:

      ${__groovy(vars.get('countries').split()[vars.get('__jm__Loop Controller__idx') as int],)}
      

      enter image description here