Search code examples
groovyjmeterbeanshell

How to get random row from file in JMeter


I'm looking for way how to get random row from file in JMeter. I would be appreciate for any suggestions.


Solution

  • Not sure regarding groovy, maybe there is an easier way, but for instance you can do it with Beanshell Sampler using the following code:

    import org.apache.commons.io.FileUtils; //necessary import
    
    List lines = FileUtils.readLines(new File("/path/to/your/file"));  // read file into lines array   
    int random = new Random().nextInt(lines.size()); // get random line number
    String randomLine = lines.get(random); // get random line
    
    vars.put("randomLine", randomLine); // store the random line into ${randomLine} variable
    
    • substitute /path/to/your/file with relative or absolute path to the file you want the random line from
    • you will be able to access the random line as ${randomLine} where required

    See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using JMeter and Java APIs from Beanshell test elements in your JMeter test

    N.B. The above code is valid groovy code as well