QA and Test Automation · Lab 7 of 35

Find and Fix a Flaky Test: Hands-On Lab on ShopRung

Take a ShopRung test suite that passes every time in its usual order, shuffle it and watch it fail, measure how often it fails, reproduce one failure exactly with its seed, find the cause (tests sharing state), fix it properly, and prove the fix. Plus the other common causes and a quarantine policy.

⏱ 45 minIntermediate💸 Free7 stepsJava + Python

Java 21 + Maven + JUnit 5.11Python 3.12 + pytest + pytest-randomly (second path)ShopRung

Overview video

1 / 6

0 of 7 steps done

What you will build

A checkout test suite for ShopRung in two versions:

  • As first written: three tests that pass every time in the order they are written, and fail in most other orders. In Python, only 2 of 10 random orders passed; in Java, 1 of the 6 possible orders.
  • Fixed: every test sets up its own data, so all orders pass: 10 of 10 seeds, and 60 of 60 when each test is repeated 20 times.

You also get a small flake_rate.py script that runs a suite many times in random orders and reports its pass rate and the seeds that failed.

Before you start

Setup

S1Start ShopRung

Start ShopRung as in lab 1 with npm start, and leave it running.

Run
curl http://localhost:8080/api/health
You should see
{"status":"UP","app":"ShopRung","version":"1.0.0"}

S2Make the project

Java: Maven folders for tests and test resources. Python: a folder with tests and a virtual environment.

Run
# Java
mkdir -p shoprung-flaky/src/test/java/dev/algorung/flaky shoprung-flaky/src/test/resources
# Python
mkdir -p shoprung-flaky-py/tests && cd shoprung-flaky-py && python3 -m venv .venv && source .venv/bin/activate
1

The project and a tiny ShopRung client

A build with JUnit only, and a helper that talks to ShopRung with the JDK's HTTP client.

Java: pom.xml needs only JUnit. Shop.java sends requests with java.net.http, so there is nothing else to install: post, get, reset and loginAlice (which pulls the token out of the response).

Python: requirements.txt adds two pytest plugins you will need: pytest-randomly, which shuffles the test order on every run and prints the seed it used, and pytest-repeat, which runs each test many times.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.algorung</groupId>
  <artifactId>shoprung-flaky</artifactId>
  <version>0.1.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>5.11.4</junit.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
    </plugins>
  </build>
</project>
src/test/java/dev/algorung/flaky/Shop.java
package dev.algorung.flaky;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/** A tiny ShopRung client: just enough HTTP for these tests, with the JDK only. */
final class Shop {
    static final String BASE_URL = System.getProperty("baseUrl", "http://localhost:8080");
    private static final HttpClient HTTP = HttpClient.newHttpClient();

    private Shop() {}

    static HttpResponse<String> post(String path, String token, String json) {
        HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE_URL + path))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json == null ? "" : json));
        if (token != null) b.header("Authorization", "Bearer " + token);
        return send(b.build());
    }

    static HttpResponse<String> get(String path, String token) {
        HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE_URL + path));
        if (token != null) b.header("Authorization", "Bearer " + token);
        return send(b.build());
    }

    static void reset() {
        post("/api/test/reset", null, null);
    }

    static String loginAlice() {
        String body = post("/api/auth/login", null,
                "{\"email\":\"alice@shoprung.test\",\"password\":\"Alice123!\"}").body();
        return body.replaceAll(".*\"token\":\"([^\"]+)\".*", "$1");
    }

    private static HttpResponse<String> send(HttpRequest request) {
        try {
            return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            throw new IllegalStateException("ShopRung is not reachable at " + BASE_URL + ": start it with npm start", e);
        }
    }
}
  1. mvn test -DbaseUrl=... for another server.line 11
  2. Puts ShopRung back to its seed data. Where you call it is the whole story of this lab.line 30
  3. Pulls the token out of the JSON without a JSON library.line 37
2

The suite as first written: always green

Three checkout tests that pass every time you run them in their usual order.

Create the test file below. It looks reasonable: reset ShopRung and log Alice in once for the whole class (or file), then three tests: add four notebooks ($50.00), apply SAVE10 (total $49.99), place the order (the cart empties).

Run it a few times. It passes every time, because the tests always run in the same order. Many real suites look exactly like this, and nobody notices the problem until the order changes: a new test is added, a framework is upgraded, or the suite is split across parallel workers.

Java note: JUnit's default order is fixed but not guaranteed to be top to bottom, so for this step run with the method-name order, which matches the numbers in the names.

src/test/java/dev/algorung/flaky/CheckoutFlowTest.java
package dev.algorung.flaky;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

/** The checkout flow, as first written. Every test passes when they run top to bottom... */
class CheckoutFlowTest {
    static String alice;

    @BeforeAll
    static void resetOnceAndLogIn() {
        Shop.reset(); // ONCE for the whole class
        alice = Shop.loginAlice();
    }

    @Test
    void test1AddFourNotebooks() {
        var r = Shop.post("/api/cart/items", alice, "{\"productId\":1,\"quantity\":4}");
        assertTrue(r.body().contains("\"subtotalCents\":5000"), r.body());
    }

    @Test
    void test2Save10AppliesAt50Dollars() {
        var r = Shop.post("/api/cart/coupon", alice, "{\"code\":\"SAVE10\"}");
        assertEquals(200, r.statusCode(), r.body());
        assertTrue(r.body().contains("\"totalCents\":4999"), r.body());
    }

    @Test
    void test3CheckoutEmptiesTheCart() {
        var r = Shop.post("/api/orders", alice, null);
        assertEquals(201, r.statusCode(), r.body());
        assertTrue(Shop.get("/api/cart", alice).body().contains("\"itemCount\":0"));
    }
}
  1. Once for the whole class. Every test shares one cart.line 13
  2. Silently needs test1 to have run first.line 26
  3. Needs a full cart, which only test1 provides.line 33
Run
mvn test -Djunit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer\$MethodName
You should seeyour text will differ: the model writes it
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
3

Shuffle the order and watch it fail

Run the same tests in a random order, read the failures, and see they are not about checkout at all.

Java: create src/test/resources/junit-platform.properties (below). It makes JUnit run test methods in a random order, decided by a seed: the same seed always gives the same order. Python: pytest-randomly is already on; it prints the seed at the top of every run.

Run with seed 1. Now the checkout test runs before anything was added: Your cart is empty. SAVE10 runs before the notebooks: This coupon needs a subtotal of at least $50.00. Neither failure is a bug in ShopRung. The tests depend on each other.

src/test/resources/junit-platform.properties
# Run test methods in a random order, so hidden dependencies between tests show up.
junit.jupiter.testmethod.order.default = org.junit.jupiter.api.MethodOrderer$Random
# The seed decides the order. Change it (or pass -Djunit.jupiter.execution.order.random.seed=7) to try another
# order; keep a failing seed to reproduce the failure exactly.
junit.jupiter.execution.order.random.seed = 1
  1. A random order for every test class.line 2
  2. The seed. Keep the one that failed: it reproduces the exact order.line 5
Run
mvn test
You should seeyour text will differ: the model writes it
[ERROR] CheckoutFlowTest.test3CheckoutEmptiesTheCart:... expected: <201> but was: <400>
  {"error":"empty_cart","message":"Your cart is empty"}
[ERROR] CheckoutFlowTest.test2Save10AppliesAt50Dollars:... expected: <200> but was: <400>
  ... "This coupon needs a subtotal of at least $50.00"
[ERROR] Tests run: 3, Failures: 2
Why this way? A test that fails depending on what ran before it is flaky even if its own code is perfect. Random order is the cheapest way to find these hidden links.
4

Measure the flakiness, and reproduce it

A pass rate across many orders, and one failing order you can replay exactly.

"It fails sometimes" is not a bug report. Measure it. In Python, flake_rate.py runs the suite 10 times with seeds 1 to 10 and prints how many runs passed and which seeds failed. On ShopRung this suite passed 2 of 10 runs.

In Java, there are only 3 tests, so there are only 6 possible orders; we ran all six against ShopRung and only 1 passed: the original order. Try a few seeds yourself with -Djunit.jupiter.execution.order.random.seed=N.

The seed is the reproduction recipe: pytest --randomly-seed=1 or the Java seed property gives the same failing order every time. Put it in the bug ticket.

Run
mvn test -Djunit.jupiter.execution.order.random.seed=2
mvn test -Djunit.jupiter.execution.order.random.seed=3
You should seeyour text will differ: the model writes it
Some seeds fail and some pass: the order changes, the code does not.
5

Fix the cause: each test owns its data

Reset before every test, and let each test arrange exactly what it needs.

The cause is shared state: one reset for the whole class, and tests that rely on what earlier tests left behind. The fix has two parts:

  1. Reset and log in before every test (@BeforeEach, or a function-scoped fixture).
  2. Each test arranges its own data. SAVE10 and checkout both need $50.00 in the cart, so they call addFourNotebooks() themselves. A test reads top to bottom as a complete story.

Notice what we did not do: no retries, no sleeps, no @Order annotations to force the old order. Those hide the problem; this removes it. Rename the methods too: the numbers suggested an order that must not matter.

src/test/java/dev/algorung/flaky/CheckoutFlowTest.java
package dev.algorung.flaky;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.net.http.HttpResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/** The checkout flow, fixed: every test sets up its own data, so any order works. */
class CheckoutFlowTest {
    String alice;

    @BeforeEach
    void resetAndLogIn() {
        Shop.reset(); // before EVERY test
        alice = Shop.loginAlice();
    }

    /** Arrange: $50.00 in the cart. Each test that needs it calls it itself. */
    private HttpResponse<String> addFourNotebooks() {
        var r = Shop.post("/api/cart/items", alice, "{\"productId\":1,\"quantity\":4}");
        assertEquals(200, r.statusCode(), r.body());
        return r;
    }

    @Test
    void addFourNotebooks_subtotalIs50Dollars() {
        assertTrue(addFourNotebooks().body().contains("\"subtotalCents\":5000"));
    }

    @Test
    void save10AppliesAt50Dollars() {
        addFourNotebooks();
        var r = Shop.post("/api/cart/coupon", alice, "{\"code\":\"SAVE10\"}");
        assertEquals(200, r.statusCode(), r.body());
        assertTrue(r.body().contains("\"totalCents\":4999"), r.body());
    }

    @Test
    void checkoutEmptiesTheCart() {
        addFourNotebooks();
        var r = Shop.post("/api/orders", alice, null);
        assertEquals(201, r.statusCode(), r.body());
        assertTrue(Shop.get("/api/cart", alice).body().contains("\"itemCount\":0"));
    }
}
  1. Before EVERY test: known data in, known results out.line 14
  2. Arrange helper: each test calls it when it needs a full cart.line 21
  3. Arrange, act, assert, all inside the test.line 41
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
6

Prove the fix

Every order passes, and every test passes 20 times in a row.

One green run proves little for a flaky test. Run it the way it failed, many times: every seed, and every test repeated. In Python, all 10 seeds passed and --count=20 ran each test 20 times: 60 passed. In Java, all 6 of 6 orders now pass; check a few seeds, and use @RepeatedTest(20) on a test if you want repeats.

Keep random order switched on for good. It costs nothing and catches the next hidden dependency the day it is written.

Run
mvn test -Djunit.jupiter.execution.order.random.seed=2
mvn test -Djunit.jupiter.execution.order.random.seed=3
You should seeyour text will differ: the model writes it
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS  (every seed)
7

The other usual suspects, and a quarantine policy

Know the main causes of flakiness and what a team does while fixing them.

Shared state is the most common cause. The others you will meet:

  • Timing: reading the page before it updates, fixed sleeps (see Waits and synchronization). Fix: wait for a condition.
  • Time and dates: a test that uses today's date fails on the day a coupon expires, or at midnight. Fix: inject a clock (the mocks lab).
  • Parallel runs: two workers using the same user. Fix: unique data per test (parallel episode).
  • Environment: a slow or shared test server, a third-party sandbox that is down. Fix: mock what you do not own, check health first.
  • Unordered results: asserting a list order the API never promised. Fix: sort, or compare as sets.

While a flaky test is being fixed, teams quarantine it: mark it (for example @Tag("quarantine") or @pytest.mark.quarantine), exclude it from the blocking run, keep running it separately, and give it an owner and a deadline. Automatic retries can be useful to keep the pipeline moving, but only if every retried pass is recorded and investigated: a retry that hides a flake also hides real intermittent bugs.

Check it works

The lab worked when both of these are true:

  • The version from step 2 fails for most random orders (Python: about 2 of 10 seeds pass; Java: only the original order of the 6 passes), and a failing seed reproduces the same failure every time.
  • The fixed version passes every seed you try, and 20 repeats of each test.
Test
python flake_rate.py 10
# Java: mvn test with seeds 1, 2 and 3
You should see
10/10 runs passed (100%)

Troubleshooting

Python: the order does not change between runs.

pytest-randomly is not installed in the active environment, or you passed -p no:randomly. pip install -r requirements.txt inside the virtual environment.

Java: the order is the same for every seed.

Check the properties file is at src/test/resources/junit-platform.properties and the class name is org.junit.jupiter.api.MethodOrderer$Random.

Every test fails with a connection error.

ShopRung is not running. Start it with npm start, or pass the base URL.

The fixed suite still fails sometimes.

Look for state outside the test: another suite or a person using the same ShopRung at the same time. Each test run needs its own environment, or its own data.

What changes in production

  • Teams track flakiness as a number: the pass rate of each test over many CI runs. Tools in CI dashboards flag tests that both pass and fail on the same commit.
  • Random test order is switched on permanently in many codebases, with the seed printed in every log.
  • Flaky tests are quarantined with an owner and a deadline, never just retried forever or deleted.
  • Independent tests (own data, no order) are also what makes parallel runs and sharding possible, which is how big suites stay fast.

Interview angle

“A test passes locally and fails in CI one run in five. How do you handle it?”

First reproduce and measure: run it many times, in random order and in parallel like CI, and record the pass rate and a failing seed or log. Then find the cause from the evidence: shared state and order dependence, timing and missing waits, dates and time zones, parallel data collisions, or an unstable environment. Fix the cause (own data per test, condition-based waits, an injected clock, unique test data) instead of adding sleeps or retries, then prove it with many repeated runs. While it is being fixed, quarantine it with an owner so the pipeline stays trustworthy.

Clean up

The full project

Every file from this lab, as it is after the last step.

Download Java project (.zip) Download Python project (.zip)