Search code examples
cookiesjmeterbeanshell

JMeter - Verify a Specific Cookie Value was Used?


So in my Test Plan I have a Cookie Manager setup inside my Thread Group which sets a specific Cookie value for 1 Cookie. Let's call it, MYID. I'm trying to figure out a way to verify that this specific Cookie's value was used to complete this one HTTP Request, because if I set my MYID to a specific value *(which actually tells which web server to go to), say to "Server1", but Server1 is down, unavailable, etc... HAProxy should change this and send you to Server2.

So basically I want to try and make sure that Cookie MYID was equal to "Server1" all the way through the HTTP Request.

I am trying to use a BeanShell PostProcessor to verify the Cookie's value after the request is ran, but when I tried using some code I have inside a PreProcessor that sets a cookie in a different Test Plan of mine I get an error saying:

Error Message:

Typed variable declaration : Attempt to resolve method: getCookieManager() on undefined variable or class name: sampler


And below here is the Code slightly modified from a BeanShell PreProcessor in another Test Plan I have...

CODE:

import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;

CookieManager manager = sampler.getCookieManager();

for (int i = 0; i < manager.getCookieCount(); i++) {
    Cookie cookie = manager.get(i);
    if (cookie.getName().equals("MYID"))    {
        if (cookie.getValue().equals("Server1")) {
            log.info("OK: The Cookie contained the Correct Server Number...");
        } else {
            log.info("ERROR: The Cookie did NOT contain the Correct Server Number...");
        }
        break;
    }
}

For the error, I was thinking the "sampler" object was no longer available since the Request was already run, or something along those lines, but I'm not sure...

Or, is there another JMeter object I should be using instead of the "BeanShell PostProcessor" in order to verify the Cookie's value was correct..?

Any thoughts or suggestion would be greatly appreciated!

Thanks in Advance,
Matt


Solution

  • If you trying to get cookie manager from the parent sampler in the Beanshell PostProcessor - you need to use ctx.getCurrentSampler(), not "sampler" as it is not exposed in script variables.

    So just change this line:

    CookieManager manager = sampler.getCookieManager();
    

    to

     CookieManager manager = ctx.getCurrentSampler().getCookieManager();
    

    And your script should start working as you expect.

    ctx is a shorthand to JMeterContext instance and getCurrentSampler() method name is self-explanatory.

    For more information on Beanshell scripting check out How to use BeanShell: JMeter's favorite built-in component guide.