Video in progress
What is a flaky test, what are its usual causes, and how do you find and fix one in CI?
A flaky test sometimes passes and sometimes fails even when the code hasn't changed. The causes are often dependence on time and order, shared state between tests, external systems, and hardcoded sleeps. To fix it, you first need to reproduce it reliably.
📖 Answer
The biggest harm of a flaky test is the loss of trust. The team gets into the habit of "if it's red, rerun it", and one day a real bug slips through the same way.
The main causes I've seen:
Thread.sleepand timeouts that aren't enough for a slow CI agent;- tests sharing data: one test writes a user to the database and another counts them with
count(); - order dependence:
HashMap/HashSetiteration, SQL results withoutORDER BY; - time: midnight, end of month, timezone (CI is in UTC, the laptop is in Tashkent);
- static state or a singleton cache that lingers between tests;
- the port is taken, or the container didn't finish starting.
Reproducing it:
# one test 50 times, stop at the first failure
for i in $(seq 50); do mvn -q test -Dtest=OrderIT -Dsurefire.rerunFailingTestsCount=0 || break; done
Temporarily putting @RepeatedTest(100) helps too. If it's order-related, I shuffle with junit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer$Random. Limiting CPU in Docker to imitate a slow CI agent also works.
On process: Surefire's rerunFailingTestsCount marks flaky tests separately as "Flakes". That's for building a list, not for hiding them. Every test on the list should have a ticket, an owner and a deadline.
Sign up to mark studied questions and save your progress.