CMM
CMM

Reputation: 573

Jmeter - How to use the variable set in first request for all the threads in one thread group

I would like to run one request only once, and get an authorization token from its response using Json extractor and then use that token as header in another request that runs under the same thread group.

I tried to use "setup Thread Group", but the variable value was not available to the main thread group. So, I used "If Controller" under the same thread group, with below condition:

${__groovy(ctx.getThreadNum() == 0 &&  vars.getIteration() == 1,)}

This is making the specific request to be executed only once. However, variable value is available only for one thread for the subsequent requests, but not for all the threads. Below is the picture of results tree:

enter image description here

May I know how to access the variable value set in first request for all the threads instead of just one thread?

Upvotes: 1

Views: 2278

Answers (2)

Dmitri T
Dmitri T

Reputation: 168002

As per JMeter Documentation:

Properties are not the same as variables. Variables are local to a thread; properties are common to all threads

So if you want to use a single token for all threads (virtual users) you need to convert it into a JMeter Property first like:

  1. Under the If Controller use __setProperty() function to convert your variable into a property
  2. In your GET request use __P() function to read the property value

Another way of sharing data between threads (even if they're in different thread groups) is using Inter-Thread Communication Plugin

Upvotes: 1

Amol Chavan
Amol Chavan

Reputation: 3970

You are not allowed to use the variable created in one thread in other threads this is how JMeter scoping for variables extracted works.

You already near to solution, providing steps so any one can approach problem like this:-

  1. Use If Controller to make sure only once request being made to get Authorization token
  2. Extract the token using post-processor
  3. Save token in the property using post-processor so that same token can get used in multiple threads
  4. Use newly created property instead of a variable in subsequent requests by referring property function instead of variable

You can use one JSR223 post-processor like below to create a property from the variable:

variable to property conversion

Please note that if you are mimicking multiple users using thread group, ideally you should create different auth token for different users.

P.S.: Balzemeter have an article which uses the BeanShell to demonstrate how to solve this problem

Upvotes: 1

Related Questions