category-iconCASE STUDY

Cut Login Time, Boost Test Speed: Cookie-Powered QA Automation

03 Aug 202511751
-688df9c0b3f0e

Logging in again and again in our test automation? That’s like unlocking our phone with a password every single time - instead of using Face ID.

Let’s automate smarter - and reuse our session like pros.


🚀 Quick Summary

  • Re-logging in on every test? Waste of time.
  • Store session cookies once → reuse them like a boss.
  • Use CookieManager.java to persist and reload cookies automatically.
  • Keep sensitive info secure with .env config.
  • Result: Lightning-fast tests with real-session behavior and less flakiness.
  • Code on GitHub: https://github.com/suraiyasathi/Automation-Test-Project


💡 Why Bother With Cookie Management?

We’ve all seen it: We run our UI automation test suite, and every single test begins with...

👉 Open site → Enter email → Enter password → Click login → Wait → Hope it worked.

Multiply that across 30+ tests, and we are looking at minutes (or hours) of wasted login steps - not to mention brittle code that breaks if the login page hiccups.

Solution?

Let’s make our tests remember that we’ve already logged in - by saving and reusing the cookies that a browser creates after login.


🍪 Meet the CookieManager - Test’s Memory Chip

We wrote a little Java utility that acts like a session-saving robot. It saves cookies to a file after a successful login, and reuses them if they’re still fresh.

🔐 What It Does

  • Saves cookies into a cookies.json file after a successful login.
  • Loads cookies back into the browser before the next test, skipping login.
  • Checks for expiry (e.g., 10 hours) so stale cookies don’t get reused.


✅ The Login Flow (Without Drama)

CookieManager cookieManager = new CookieManager(driver);
boolean loaded = cookieManager.loadCookiesIfValid();
if (loaded)) {
    driver.navigate().refresh(); // Apply loaded cookies
} else {
    loginPage.login(EMAIL, PASSWORD); // Manual login once
    cookieManager.saveCookies(); // Save cookies for future
}

First run? It logs in and saves cookies.

Next run? It skips login like a browser that remembers.

If the cookie file is missing, expired, or empty - we log in manually and save a fresh batch of cookies.


🔄 CookieManager.java : Reuse Login Like a Pro

This class does all the heavy lifting for cookie read/write.

private static final Type COOKIE_TYPE = new TypeToken<Set<Map<String, Object>>>(){}.getType();
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();

🧠 What does this mean?

  • COOKIE_TYPE : helps Gson understand the structure of our JSON (Set<Map<String, Object>>).
  • gson : converts between cookies and human-readable JSON (pretty printed!).


🕐 Loading Cookies (If Still Fresh)

public boolean loadCookiesIfValid() {
    if (!cookieFile.exists()) return false;

    if (Instant.now().toEpochMilli() - cookieFile.lastModified() > EXPIRY_DURATION_MS) {
        System.out.println("Cookies expired.");
        return false;
    }

    try (Reader reader = new FileReader(cookieFile)) {
        Set<Map<String, Object>> rawCookies = gson.fromJson(reader, COOKIE_TYPE);
        if (rawCookies == null || rawCookies.isEmpty()) {
            return false;
        }

        rawCookies.forEach(c -> {
            Cookie cookie = new Cookie.Builder((String) c.get("name"), (String) c.get("value"))
                    .domain((String) c.get("domain"))
                    .path((String) c.get("path"))
                    .expiresOn(c.get("expiry") != null ? new Date(((Double) c.get("expiry")).longValue()) : null)
                    .isSecure((Boolean) c.getOrDefault("isSecure", false))
                    .isHttpOnly((Boolean) c.getOrDefault("isHttpOnly", false))
                    .build();
            driver.manage().addCookie(cookie);
        });
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

🧪 We read the cookies from file if:

  • The file exists ✅
  • The cookies are not older than 10 hours
  • The cookies are valid ✅


💾 Saving Cookies

public void saveCookies() {
    Set<Cookie> cookies = driver.manage().getCookies();
    if (cookies.isEmpty()) {
        return;
    }

    Set<Map<String, Object>> simplified = new HashSet<>();
    cookies.forEach(c -> {
        Map<String, Object> map = new HashMap<>();
        map.put("name", c.getName());
        map.put("value", c.getValue());
        map.put("domain", c.getDomain());
        map.put("path", c.getPath());
        map.put("expiry", c.getExpiry() != null ? c.getExpiry().getTime() : null);
        map.put("isSecure", c.isSecure());
        map.put("isHttpOnly", c.isHttpOnly());
        simplified.add(map);
    });

    try (Writer writer = new FileWriter(cookieFile)) {
        gson.toJson(simplified, writer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

🍪 Converts live session cookies to simplified maps → saves them as pretty JSON.

It’s browser session preservation magic.


🔐 Wait… Where’s the Login Info?

Instead of hardcoding emails, passwords, or URLs in the code, we keep them in a .env file:

BASE_URL = https://www.automationexercise.com/
EMAIL = [email protected]
PASSWORD = mySuperSecret123
USERNAME = Test User
BROWSER = chrome
HEADLESS = true

Then we use a handy utility to load them safely:

private static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load();

🔍 This line loads the .env file into memory and ignores it if missing, which is helpful in CI/CD pipelines or local debugging.

The helper methods:

public static String get(String key) { ... }
public static String get(String key, String defaultVal) { ... }
public static boolean getBoolean(String key, boolean defaultVal) { ... }

✅ Let us grab strings or booleans from the environment easily.


📦 Dependencies We'll Need

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.10.1</version>
</dependency>
      
<!-- https://mvnrepository.com/artifact/io.github.cdimascio/dotenv-java -->
<dependency>
  <groupId>io.github.cdimascio</groupId>
  <artifactId>dotenv-java</artifactId>
  <version>3.0.0</version>
</dependency>

We use two handy dependencies to power this cookie-powered login shortcut: Gson (com.google.code.gson:gson:2.10.1) helps us convert cookies to and from JSON format so we can store them in a readable file, while dotenv-java (io.github.cdimascio:dotenv-java:3.0.0) lets us securely load environment variables like base URL, login credentials, and browser config from a .env file - keeping our secrets out of the code and our setup clean.


🎯 Final Bytes - Because Life’s Too Short to Click Login Repeatedly

  • Let’s be honest: logging in manually every time during test runs feels like a mild form of digital punishment.
  • But with cookie management, we're basically saying: “Remember me forever… or at least for 10 hours.”
  • We’ve also cleaned up our mess by using a .env file - because hardcoding credentials is like leaving our keys under the welcome mat.

So next time someone says,

“Can’t you just automate the login?”
You can confidently reply:
“Been there. Cookied that.” 🍪😎

Keep testing smart, not hard. Happy automating!