Search code examples
jmeterbeanshell

How to pass data to BeanShell sampler using BeanShell preprocessor using JMeter?


I need to read file once and its result to be processed further in sampler. My strategy is ThreadGroup--> BeanShell Preprocessor + BeanShell Sampler

My preprocessor should read file once for whole Thread Group and result to be used in Sampler for specific no. of thread.(i do not want to read file for each thread)

I wrote file reader code in preprocessor, now need to use the result in sampler.


Solution

    1. Don't use the Beanshell PreProcessor as it will be executed by each thread. Use a separate Thread Group with 1 thread to read the values.
    2. Don't use Beanshell Samplers to create the actual load, in case of more or less severe load it will become a bottleneck.
    3. Use JSR223 Test Elements and "groovy" language for scripting - this way you'll be able to get maximum performance from your code.

    Now answers:

    int number = ctx.getThread().getThreadNum(); // get current thread number
    
    props.put("value_for_thread_" + number, "foo"); // store some value specific for the specific thread
    
    String value = props.get("value_for_thread_5"); // get value for thread 5
    

    Where:

    • ctx - is a shorthand for JMeterContext
    • props - stands for JMeter Properties, an instance of java.util.Properties deriving all the methods and fields, global for the whole JVM instance.

    See JavaDocs for aforementioned objects to see what else can be done and Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! guide for instructions on installing groovy scripting engine, scripting best practices and benchmark of Beanshell, JSR223+groovy and Java code.