Friday, June 23, 2017

How to share variables between threads groups in JMeter

Sometimes when we writing jmeter scripts , we need to share variables between  threads groups in a test plan.  Easiest way to achieve this is use "bsh.shared" shared namespace.
Test Plan
        Thread Group1
        Thread Group2
Assume that you have a test scenario to  pass  the session  of the  Thread Group1 to Thread Group2  in order to create a cookie from  that session.  In order to achive that here I use hashmap
1 Initialize hash map inside a BeanShell Sampler  in top level of Test plan
Map map = new HashMap();
2.  Extract the session and  in a  BeanShell PostProcessor set bsh.shared to map and add session values in Thread Group1
String sessionId = vars.get("SSOAuthSessionID"); // exctracted session
map = bsh.shared.session_map; // set bsh.shared to map
if ("null".equals(sessionId)) {
} else {
  String id = vars.get("sessionID_count"); // I have added a counter varibale  as the key
  map.put(id, sessionId); //Adding elements toMap
}
3. Retrieve the values in bash.shared.session map using BeanShell PreProcessor in Thread Group 2 and create
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
map = bsh.shared.session_map;
String id = vars.get("sessionID_count2"); //I have added a counter varibale  as the key
if (map.size() == 0) {} else {
 String sessionId = map.get(id);
 vars.put("portal_session_", sessionId); //Retrieving values in bash.shared.session  
 CookieManager manager = sampler.getCookieManager();
 Cookie cookie = new Cookie("JSESSIONID", sessionId, "${serverHostName}", "/user-portal/", false, 0);
 manager.add(cookie); //
}
Hope that this will find helpful for you.




2 comments :

  1. can you help me pass a cookie from thread1 to thread2

    ReplyDelete
  2. I am using Jmeter5.2.1 , I am not able to create a bean shell sampler at test plan level. can you please help.

    ReplyDelete