Mohamed Omezzine
Mohamed Omezzine

Reputation: 1104

Get random values from an array

I defined a new variable

Name        Value            Description
categories  (1, 2, 3, 4, 5)  my categories ids

and in my path i want to get a random value from categories: category_id=my_random_value.

I even tried this

category_id=${__StringFromArrayAtRandomindex('1', '2', '3', '4', '5'}

but it doesn't work.

Upvotes: 15

Views: 34217

Answers (3)

Aliaksandr Belik
Aliaksandr Belik

Reputation: 12873

For your scenario you could try to use the JSR233 components (Sampler, PreProcessor, PostProcessor) with a bit of java/groovy code.

E.g.:

  • Define your data as you've done:

    Name        Value          
    categories  1,2,3,4,5
    

    (i.e. use comma as delimiter, no spaces before and after comma).

  • Use the JSR233 Sampler / PreProcessor / PostProcessor with the following code:

    import java.util.Random;
    
    String[] categories = (vars.get("categories")).split(",");
    
    int idx = new Random().nextInt(categories.length);
    String category = (categories[idx]);
    
    vars.put("rnd_cat", category);
    
  • Refer to the randomly picked category using ${rnd_cat}.

Upvotes: 18

AlexGuti
AlexGuti

Reputation: 3243

To obtain a random variable value from a list, first declare as User variables the list or available values, with a prefix and a incremental index:

country_1     Spain 
country_2     France  
country_3     Portugal  
country_4     Italy 
country_5     England

Then you can obtain a random value from the list concatenating the prefix with a random index in the interval:

${__V(country_${__Random(1,6,)})}  --> "Spain", "France", "Portugal", etc...

Explanation

The __Random function will give you an index for your interval. To obtain values from 1 to 5, you have to call __Random(1,6,), as it will never reach the MAX value.

The __V function, will obtain the value of the variable with the given name.

${__Random(1,6,)}                 --> 1, 2, 3, 4, 5
country_${__Random(1,6,)}         --> "country_1", "country_2", etc...
${__V(country_${__Random(1,6,)})} --> "Spain", "France", "Portugal", etc...

As example, to use the random variable as JSON body for a request, in Body Data:

}
  "country":"${__V(country_${__Random(1,6,)})}"
}

Upvotes: 29

UBIK LOAD PACK
UBIK LOAD PACK

Reputation: 34556

__StringFromArrayAtRandomindex is not part of JMeter core nor part of JMeter plugins.

Is it a custom function ?

Furthermore, you have a syntax error (there is a missing ) at end:

${__StringFromArrayAtRandomindex('1', '2', '3', '4', '5')}

To do the same thing, use a CSV Data Set which will contain:

1
2
3
4
5

Set:

Variable Names=categoryId

You can then use it like this:

${categoryId} 

Upvotes: 9

Related Questions