Home » Blog » Cookies in Gatling: A Comprehensive Guide

Cookies in Gatling: A Comprehensive Guide

Recently, while working with a client, there arose a need to reterive value for cookies in Gatling to enhance the debugging capabilities of application failures. A usual search in Google for cookies-related queries did not yield much helpful information. However, I observed that many Gatling users face a similar challenge, struggling to retrieve cookie values to enhance their debugging capabilities.

Therefore, this blog serves as a comprehensive guide to assist you in handling cookies in Gatling tests.

Adding Cookies in Gatling Tests

Note – Example code snippets are in Java.

Add Basic Cookie

A cookie value can be added in a Gatling test by using the addCookie DSL.

Pro-tip #1

   public ScenarioBuilder registerUser = scenario("Register User")
            .exec(addCookie(Cookie("language", "pl"))) // Add Basic Cookie
            .exec(http("GET-/register").get("#/register"))
            .exec(session -> {
                System.out.println("### Gatling Cookie ###");
                System.out.println(session.asScala().attributes().get("gatling.http.cookies"));
                return session;
            });

Add Cookie in Gatling test with additional details

A sample code to add cookie with additional details like domain, path, expiry, etc.

  • domain is optional, defaulting to base url domain
  • path is optional, defaulting to “/”
  • maxAge is and optional number of seconds, defaulting to Long.MinValue
  • secure is optional, defaulting to false
public ScenarioBuilder registerUser = scenario("Register User")
            .exec(addCookie(Cookie("language", "pl").withPath("/callback").withMaxAge(30))) 
            .exec(http("GET-/register").get("#/register"))
            .exec(session -> {
                System.out.println("### Gatling Cookie ###");
                System.out.println(session.asScala().attributes().get("gatling.http.cookies"));
                return session;
            });

Add Cookie in Gatling based on a Condition

public ScenarioBuilder registerUser = scenario("Register User")
            .doIfEquals("#{userName}", "admin")
            .then(exec(addCookie(Cookie("language", "pl")))) 
            .exec(http("GET-/register").get("#/register"))
            .exec(session -> {
                System.out.println("### Gatling Cookie ###");
                System.out.println(session.asScala().attributes().get("gatling.http.cookies"));
                return session;
            });

Add Cookie in Gatling using Session value

public ScenarioBuilder registerUser = scenario("Register User")
            .exec(addCookie(Cookie(session -> session.getString("cookieName"),
                    session -> session.getString("cookieValue"))))
            .exec(http("GET-/register").get("#/register"))
            .exec(session -> {
                System.out.println("### Gatling Cookie ###");
                System.out.println(session.asScala().attributes().get("gatling.http.cookies"));
                return session;
            });

Retrieving Cookie Value

Pro-tip #2

There is no direct and easy way to retrieve a cookie’s value in Gatling. Only the cookie that is set in the test explicitly can be easily retrieved using Gatling DSL.

How to retrieve Cookie Value

As mentioned above, only the cookie set explicitly in the test can be retrieved by Gatling DSL getCookieValue.

 public ScenarioBuilder registerUser = scenario("Register User")
            .exec(addCookie(Cookie("language", "pl")))
            .exec(http("GET-/register").get("#/register"))
            .exec(getCookieValue(CookieKey("language")))
            .exec(session -> {
                System.out.println("Print Cookie Value");
                System.out.println(session.getString("language"));
                return session;
            });

How to debug Cookies set in Gatling Session

The cookie set by the application can be debugged using Gatling Session. To debug which cookies are present in Gatling, one can use a code snippet as below. However, there is no direct DSL to get the value of a cookie set by the server.

public ScenarioBuilder registerUser = scenario("Register User")
            .exec(http("GET-/register").get("#/register"))
            .exec(session -> {
                System.out.println("### Gatling Cookie ###");
                System.out.println(session.asScala().attributes().get("gatling.http.cookies"));
                return session;
            });

Output for above

CookieJar(Map(CookieKey(language,localhost,/) -> StoredCookie(language=pl,true,false,1709710948891)))

Debugging Set-Cookie header

Below would save the value of Set-Cookie header in session which can be printed out later for debugging purpose.

check(header("Set-Cookie").saveAs("setCookie"))

Logging the API Calls to debug Gatling Cookies

Another way to debug cookies would be by logging the request and response of API calls made by Gatling. For that purpose, one can add a logback-test.xml file in the test/resources directory with the below content. This will log detailed network calls in the execution.log file, aiding in debugging which cookies are present in the API calls.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
        </encoder>
        <immediateFlush>false</immediateFlush>
    </appender>

    <appender name="ERROR" class="ch.qos.logback.core.FileAppender">
        <file>${logFilePath:-execution.log}</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
        </encoder>
        <immediateFlush>false</immediateFlush>
        <param name="Append" value="false" />
    </appender>

    <logger name="io.gatling.http.ahc" level="TRACE" additivity="false">
        <appender-ref ref="ERROR"/>
    </logger>
    <logger name="io.gatling.http.response" level="TRACE" additivity="false">
        <appender-ref ref="ERROR"/>
    </logger>
    <logger name="io.gatling.http.engine.response" level="TRACE" additivity="false">
        <appender-ref ref="ERROR"/>
    </logger>

    <root level="WARN">
        <appender-ref ref="CONSOLE" />
    </root>

</configuration>

Read about different configurations available for the Gatling Maven Plugin.

FAQ

How to add a Cookie from Gatling Test?

In order to add a cookie from Gatling Test, You can use addCookie DSL provided by Gatling. Example code:

public ScenarioBuilder registerUser = scenario("Register User")
.exec(addCookie(Cookie("language", "pl")))
.exec(http("GET-/register").get("#/register"))
.exec(session -> {
System.out.println("### Gatling Cookie ###");
System.out.println(session.asScala().attributes().get("gatling.http.cookies"));
return session;
});

How to retrieve Cookie value in Gatling?

The easiest way to retrieve cookie value in Gatling is using a code like exec(getCookieValue(CookieKey("language"))). But this works only if the cookie was added in the test explicitly by using Gatling DSL addCookie. If you are trying to retrieve the value of a cookie which is added by application then this DSL won’t work.

Your subscription encourages me to write more insightful articles.

Subscribe to my newsletter and explore Quality Assurance beyond just manual and automation testing!

We don’t spam! Read our privacy policy for more info.

Thank you for reading this post, don't forget to subscribe!

Priyanshu S
Priyanshu S

QA Consultant | Quality Advocate | Currently working with Equal Experts

Articles: 30

Leave a Reply