Skip to content

Flaky tests: a triage routine that finds the cause instead of re-running

A flaky test passes and fails on the same code. Reproduce it, classify the cause, fix it, and never accept “re-run” as an answer. A routine for teams.

Published by Contextingo.

A flaky test gives different results on the same code. Re-running hides the problem and teaches the team to ignore red builds.

Common causes

  • Timing: a fixed sleep, a race, a timeout that is too tight.
  • Shared state: tests that depend on order or on data left by another test.
  • Time and randomness: dates, time zones, random seeds.
  • External services: network calls to something that is sometimes slow.
  • Resources: ports, files and databases used by parallel tests.

Routine

  1. Reproduce: run the test many times in a loop, alone and with the whole suite.
  2. Classify the cause using the list above.
  3. Fix the cause: wait on a condition instead of a sleep, isolate state, freeze the clock, stub the service.
  4. If a fix is not possible today, quarantine the test with a ticket and a date, so it is not forgotten.
  5. Write the cause as a finding, so a similar flake is recognised faster next time.

With an agent

An agent can run the loop and propose a cause. Check that it fixed the cause and did not add a retry or weaken the assertion. Deleting or skipping the test is not a fix.

Questions

Good to know.

Is a retry ever acceptable?

For calls to an external service in an integration test, a bounded retry can be. For a race in your own code it hides a bug.

How do I find the order dependency?

Run the tests in random or reverse order and see which one fails.

Nothing learned is lost. Nothing unchecked is done.