Video in progress

Tests in CI are sometimes red and sometimes green (flaky). How do you handle that, and what are the usual causes in Java tests?

Ignoring a flaky test with "it passes if you rerun it" kills trust in the pipeline. I identify it, move it to quarantine and give it an owner. In Java the causes are most often time, test order, shared state, async code and external resources.

📖 Answer

One flaky test turns 5% of builds red. With ten such tests, it is almost every second build. People get used to pressing "Re-run", and one day they wave a real regression through the same way.

The process:

  1. Identify: save CI test results (JUnit XML) and mark tests that both passed and failed on the same commit. Develocity or a simple script does this.
  2. Quarantine: take the test out of the main gate with @Tag("flaky"), but keep running it in a separate job. Do not delete it.
  3. Owner and deadline: a ticket, someone responsible, a week or two. Quarantine must not become a graveyard.

Surefire's -Dsurefire.rerunFailingTestsCount=2 is only a temporary relief. It hides the flaky tests, though the report marks them as "flake", and you should still review that list.

Typical causes in Java:

  • waiting for an async result with Thread.sleep(500). The CI runner is slower, and 500 ms is not enough;
  • LocalDate.now(): fails around midnight or on a runner in another timezone. Inject a Clock;
  • dependence on test order: one test leaves a record in the DB and another is not ready for it. JUnit 5 does not guarantee an order;
  • changing the state of a bean in the Spring context cache (you needed @DirtiesContext or to restore the state);
  • relying on HashMap/HashSet iteration order;
  • depending on a real port, an external service or the internet.

Awaitility for async waits:

await().atMost(Duration.ofSeconds(10))
       .untilAsserted(() -> assertThat(repo.findByOrderId(id)).isPresent());

The metric to watch: what percentage of failures on the main branch are flaky. If that number is growing, spend time on test quality before building new features.