jmeter

JMeter set variable to random option


I've been using JMeter and I'm aware of the __Random and __RandomString functions. I need to pick a random option and store it in a variable because it will be used as part of a parameter path for multiple calls. For example:

http://www.example.com/pets/{random option such as: cat, dog, parakeet}/

I've tried doing simple like this, where I set the variable ${query} to one, two, or three using a random controller with userdefined variables as children. This seems like it should work, however I always get ${query} set to three.

Any insight or ideas are will be well recieved. Thanks to all in advance.


Solution

  • You can use Beanshell Pre Processor to generate random value

    String[] query = new String[]{"cat", "dog", "parakeet"};
    Random random = new Random();
    int i = random.nextInt(query.length);
    vars.put("randomOption",query[i]);
    

    After that in your HTTP Request:

    http://www.example.com/pets/${randomOption}
    

    As an alternative to String[] query = new String[]{"cat", "dog", "parakeet"}; you can use Beanshell pre-defined Parameters stanza.

    Random random = new Random();
    int i = random.nextInt(query.length);
    vars.put("randomOption",bsh.args[i]);