JMeter Pass Variables Between Thread Groups
In this JMeter tutorial, we look at how we can share and pass variables between thread groups.
When developing advanced JMeter scripts, most likely you will have multiple thread groups. Each thread groups will be performing different requests.
A good example of this is when we need to authenticate users with Bearer Tokens. One thread group does the authentication and saves the token. Another thread group needs to access this token and use it in another request.
Therefore, we need a mechanism to pass variables between thread groups.
Pass Variables Between Thread Groups in JMeter
For this example, our test plan will have two thread groups. The first thread group makes a GET request to a web service. We then use the JSON Extractor plugin to parse the JSON response.
Using JSONPath, we extract the value for a particular key and save it as a JMeter variable.
This is how our JMeter request looks like:
The result of the above request produces the following response in JSON format:
and our JSONPath to extract the first url looks like:
The value of the JSONPath query is saved as first_url
. This variable is only accessible within the same thread group and we can get its value by using ${first_url}
. Now, how are we going to make this variable accessible via other thread groups?
The answer is to use BeanShell Assertion
to save the variable as a global property. In this way, we can pass variables between thread groups.
To add a BeanShell Assertion, right click on Test Plan > Add > Assertion > BeanShell Assertion
In our BeanShell Assertion, we can enter the following code
${__setProperty(first_url, ${first_url})};
Now in thread group 2, we can access this variable directly by using ${__property(first_url)}
as shown below:
Or, we can use a BeanShell PreProcessor
to manipulate the variable:
In the BeanShell PreProcessor, we can access the variable passed in from another Thread group, by using props.get("name_of_variable")
. We can then perform some String manipulation and save the result as a new variable.
In the example above, we remove the http://
from the variable which was passed from Thread Group 1, and we save the result as variable host
.
The variable host
is now local to Thread Group 2 and directly access it by using ${host}
as shown below: