jmeterbeanshell

i have extracted some values using regex in beanshell postprocessor now i have to pick a random value and store it into a varaible?




import java.util.Random;
import java.util.regex.Pattern;
 import java.util.regex.Matcher;


String responseData = prev.getResponseDataAsString();
// log.info("the response data is : " + responseData);

Pattern pattern = Pattern.compile("<option value=\"(.+?)\">(.+?)</option>");
// log.info("pattern is : " + pattern);
Matcher matcher = pattern.matcher(responseData);
// log.info("matcher is :" + matcher);

while(matcher.find())
{
    log.info("the cities are : " + matcher.group(1));
    String extractedCity = matcher.group(1);
    log.info("the extracted city is : " + extractedCity);
    vars.put("Depart_city" , extractedCity);
}[log level output of the code](https://i.sstatic.net/ANKbl.png)

i am able to extract the data but i am unable to pick a random value from the result and store it into a jmeter variaable


Solution

    1. You're overwriting the value on each match, you should rather store them into a List and then get the random item from the list, something like:

      import java.util.Random;
      import java.util.regex.Pattern;
      import java.util.regex.Matcher;
      import org.apache.commons.lang.math.RandomUtils;
      
      
      String responseData = prev.getResponseDataAsString();
      // log.info("the response data is : " + responseData);
      
      Pattern pattern = Pattern.compile("<option value=\"(.+?)\">(.+?)</option>");
      // log.info("pattern is : " + pattern);
      Matcher matcher = pattern.matcher(responseData);
      // log.info("matcher is :" + matcher);
      List cities = new ArrayList();
      while(matcher.find())
      {
          log.info("the cities are : " + matcher.group(1));
          String extractedCity = matcher.group(1);
          log.info("the extracted city is : " + extractedCity);
          cities.add(extractedCity);
      }
      vars.put("Depart_city", cities.get(RandomUtils.nextInt(cities.size())));
      
    2. Using Beanshell is some form of a performance ant-pattern, since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting

    3. Using regular expressions for parsing HTML is not the best idea, you could rather go for jsoup library

    4. And last but not the least, you don't need any scripting at all, you could get the random city from the response into a JMeter Variable using CSS Selector Extractor:

      enter image description here