How to generate random number using beanshell post processor in JMeter

Naseem picture Naseem · May 9, 2017 · Viewed 7.6k times · Source

I am trying to generate a random number using beanshell post processor but I am continuously getting an error

 "ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval   In file: inline evaluation of: `` try {....."

I am fetching the total count of matching records through Regular Expression extractor and passing the variable to the Post processor but it's not working.

Please see the screenshot.Regular Expresssion Extractor Beanshell Script

Answer

Dmitri T picture Dmitri T · May 9, 2017
  1. Don't inline functions and/or variables in form of ${CountID} into Beanshell scripts as they may resolve into something which will cause compilation error or other form of unexpected behaviour. Replace this line:

    int count = ${__Random(1,counter,)};
    

    with this one

    int count = ThreadLocalRandom.current().nextInt(1, counter);
    
  2. log.info(count); line won't work as you cannot print an integer to jmeter.log file, you need to cast it to String first so change this line to

    log.info(String.valueOf(count));
    
  3. Consider using JSR223 Elements and Groovy language instead of Beanshell as Beanshell interpreter has worse performance than Groovy engine.


If your target is to get a random match you can do it without any scripting using only JMeter Functions like:

${__V(countID_${__Random(1,${countID_matchNr},)})}

See Here’s What to Do to Combine Multiple JMeter Variables guide for more details.