Flaky tests: causes, diagnosis, artifacts and Allure
A flaky test sometimes passes and sometimes fails on the same code, and the cause is almost always an implicit assumption about time, order or state. Typical causes are wrong waits, dependencies between tests, unstable locators and the environment. It is diagnosed by reproducing in a loop and comparing failed runs with green ones using artifacts. A retry is acceptable only temporarily and marked flaky.
Selenium · Stability
A test fails once in ten runs. "Rerun it and it goes green". Why is that worse than it looks?
A nightly run shows three red tests out of four hundred. A developer reruns the job and everything is green. This repeats for a week and the suite loses trust: red no longer means anything, and a real defect that would stand out at first glance drowns in noise. A flaky test is one that sometimes passes and sometimes fails on the same code. It is cured, not "rerun until green". The lesson covers typical causes in Selenium tests, the order of diagnosis, the artifacts that must be collected automatically, and Allure.
How it works and why. Instability almost always means the test has an implicit assumption about time, order or state that sometimes does not hold. Typical causes in Selenium:
- wrong waits:
Thread.sleep, a click before the element is clickable, a check before an asynchronous request finishes (the lesson “Waits: implicit, explicit, fluent”); - dependencies between tests: shared data, execution order, someone else's state in the database (the lesson “Parallel runs: a driver per thread, isolation, CI”);
- unstable locators: indexes, generated classes, text that gets edited (the lesson “Locators: By, CSS versus XPath, relative locators”);
- environment: slow CI, little browser memory in a container, external services without stubs, time and time zones;
- animations and overlays: an element is moving or covered by a spinner exactly at the moment of the click.
Diagnosis is a discipline, not a guess. The order is:
The diagnosis order
Example: from "sometimes red" to the cause. First step: reproduce and estimate the frequency. A single run proves nothing, so the test is repeated in a loop:
// reproduction: the same test 30 times to see the frequency
@RepeatedTest(30)
void paymentShowsStatus() {
// ... the ordinary test unchanged
}
The test fails 4 of 30 runs. Next, failed runs are compared with green ones: what was on the page, what the browser wrote, what the server replied, how long each step took. For this, artifacts must be collected automatically at every failure: a screenshot (((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)), the URL, the page source, logs, and in Grid also a video. The most convenient place is a JUnit 5 AfterTestExecutionCallback extension: it runs before @AfterEach, so the driver is still open, and the test's exception is available through context.getExecutionException().
public class ArtifactsOnFailure implements AfterTestExecutionCallback {
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
if (context.getExecutionException().isEmpty()) {
return; // the test passed
}
WebDriver driver = Browser.get(); // the driver is still open
if (driver == null) {
return;
}
byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
String name = context.getRequiredTestMethod().getName();
Path dir = Path.of("target", "artifacts");
Files.createDirectories(dir);
Files.write(dir.resolve(name + ".png"), png);
Files.writeString(dir.resolve(name + ".html"), driver.getPageSource());
Allure.attachment("screenshot", new ByteArrayInputStream(png));
}
}
@ExtendWith(ArtifactsOnFailure.class)
abstract class BaseTest { /* ... */ }
For TestNG the analogue is ITestListener.onTestFailure. The TestWatcher extension works only if the extension itself calls quit() after the screenshot: its methods run after @AfterEach, so a driver closed there is already gone. A screenshot in @AfterEach under an "if failed" condition without an extension turns out clumsy, and people forget about it.
A screenshot in a green run says nothing, and in a failed one it shows what was on screen: a spinner over the button, a modal, a validation error, an empty table. That is usually enough to assign the cause to one of the groups above. If not, look at browser logs (events from the console through BiDi are in the lesson “BiDi instead of CDP, Actions, files, iframes and windows”) and server responses for the same time.
Allure. Allure collects this into a report. For JUnit 5 you add allure-jupiter (it replaced allure-junit5 in Allure Java 2.35.1, and the new 3.0 line no longer publishes it), for TestNG allure-testng. Steps are marked with @Step, attachments are added through Allure.attachment(...). @Step and @Attachment need AspectJ passed as a -javaagent (in Maven through the Surefire argLine). Results go to allure-results (the directory is set by allure.properties), and HTML is built by allure generate, viewed with allure open or straight away with allure serve.
public class CheckoutPage {
@Step("Pay for the order with card {card}")
public ReceiptPage payWith(String card) {
// ... page steps
return new ReceiptPage(driver);
}
}
The run history in Allure shows which tests are unstable: a single test blinking between red and green stands out at once.
Limits and alternatives. An automatic retry is acceptable as a temporary measure but is not a cure: it lowers the noise, not the cause. What matters is that the rerun is transparent. Surefire counts a test that passed on a rerun as a "flake", and this is visible in the summary:
# rerun failed tests at the Surefire level: the summary
# counts them as "flakes", not as plain successes
mvn test -Dsurefire.rerunFailingTestsCount=2
If a retry silently turns everything green, real defects hide: instability in the application (a race, data loss) looks exactly like test instability. A test whose cause is not found yet is moved to quarantine: it runs separately and does not block the build, and a ticket with an owner and a deadline is created for it. A quarantine with no deadline turns into a graveyard.
Common mistakes.
- "Curing" by raising timeouts and sleeps: the test is slower and the race stays.
- Not collecting artifacts on failure: the cause has to be guessed because nothing was kept.
- Rerunning the job until green without recording that there was a failure: the instability statistics vanish.
- Fixing only the symptom (adding a wait) without checking whether the cause is a dependency between tests or the data.
Check yourself
A test fails 3 of 20 runs, and in the failed run's screenshot the "Pay" button is covered by a spinner. Which cause group, and what is the fix?
Answer
Wrong waits: the click happens before the overlay disappears. The fix: before the click wait for invisibilityOfElementLocated of the spinner and only then for elementToBeClickable. Raising a sleep does not cure the cause.
Why does a TestWatcher extension miss the failure screenshot when quit() is in @AfterEach, while AfterTestExecutionCallback does not?
Answer
TestWatcher is called after @AfterEach, when the driver is usually already closed, so there is nothing to capture. AfterTestExecutionCallback runs right after the test and before @AfterEach: the driver is open and the test exception is available through context.getExecutionException(). If quit() moves into the extension itself, after the screenshot, TestWatcher works too.