Belinda Xu
Belinda Xu

Reputation: 35

How to transfer a variable in java sampler to jmeter?

I wonder how can I transfer a variable in a java Sampler to jmeter variable, so the next test case which may be another kind of sampler can use this data come from other case. resJson = JSONObject.parseObject(result); resJson.get("responseCode")

I try to find a method in JavaSamplerContext to transfer variable from java sampler to jmeter variable, it do not exist.

Thank you very much!

Upvotes: 1

Views: 1134

Answers (1)

Dmitri T
Dmitri T

Reputation: 168157

Since JMeter 4.0, check out JavaSamplerContext.getJMeterVariables() function

  1. Set a JMeter Variable:

     @Override
    public SampleResult runTest(JavaSamplerContext context) {
        context.getJMeterVariables().put("foo","bar")
    }
    
  2. Get a JMeter Variable:

    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        String foo = context.getJMeterVariables().get("foo");
    }
    

You might find using JSR223 Sampler and Groovy language easier to use as it provides vars shorthand which stands for JMeterVariables class instance. Well-behaved Groovy scripts have nearly the same performance as native Java code and you will not have to recompile the classes, update libraries in JMeter classpath and so on.

Upvotes: 1

Related Questions