Test Automation Interview Questions: Flaky Test Diagnosis

Reviewed by Mark Dickie · Last updated

5 questions on this page you can answer and see marked on the spot. Go to the first one

Flaky test diagnosis is the process of identifying why a test produces non-deterministic pass or fail results when the underlying code has not changed. For a test automation interview, expect to explain common root causes such as improper waits, shared mutable state, test order dependencies, and environmental variability. You should be able to describe how to isolate a flaky test from a real regression and walk through a systematic debugging approach. Interviewers also want to see you discuss flake rate and quarantine strategy, and tell a flaky test apart from a genuine failure.

What are the most common causes of flaky tests?

Root causeMechanismTypical fix
Improper waitsHard-coded sleeps or missing await callsUse explicit waits on conditions, not fixed durations
Shared stateOne test mutates data another test readsReset state in beforeEach; isolate databases or fixtures
Test order dependencyTest B depends on Test A running firstMake each test independent; never rely on execution order
Timing or race conditionsAsync operations not resolved before assertionsAwait the promise or use done/sync helpers correctly
Environment flakinessNetwork latency, API throttling, CI resource contentionMock external calls; run on dedicated CI runners

How do you systematically diagnose a flaky test?

  1. Reproduce the flake by running the test in a loop (50 to 100 iterations) and capture which runs fail.
  2. Compare failing runs' logs, screenshots, and stack traces against passing runs to spot divergences.
  3. Check whether the failure correlates with a specific test order. Shuffle execution and see if different orderings produce failures.
  4. Inspect shared resources: databases, caches, file paths, or global variables that prior tests may have left dirty.
  5. Review every wait and async call in the test to confirm no implicit timing assumptions.
  6. If the flake persists, quarantine the test so it stops blocking the pipeline while you investigate the root cause.

How do you measure and report flakiness?

Flake rate is the percentage of test runs that produce inconsistent results over a given window. You calculate it by running the same test suite multiple times against the same commit and dividing non-deterministic outcomes by total runs. A test that fails 3 out of 50 identical runs has a 6% flake rate. Most CI systems and reporting tools (Allure, ReportPortal, GitHub Actions rerun annotations) can surface this metric automatically once you enable retry tracking. Set a threshold, commonly 2 to 5%, above which a test is quarantined until the rate drops.

Key facts

  • Tarmac's Test Automation interview questions cover 24 questions at difficulty 1–5 of 5.
  • Tarmac tracked 782 job postings asking for Test Automation in September 2026.
  • Roles asking for Test Automation advertise a median base salary of £71,250, across 166 job postings as of September 2026.
  • Tarmac last reviewed these Test Automation interview questions on 14 October 2026.

At a glance

Questions24
Difficulty1–5 of 5
FormatsTrue / false, Multiple answer, Short answer, Fill in the blank, Multiple choice

What you'll review

  1. flaky test diagnosis

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

A flaky test is one that can produce both passing and failing results when run multiple times against the exact same version of the code, with no changes to the code or the test itself.#

Options

Show answer

A flaky test is a test that can both pass and fail when run repeatedly against the exact same code and test code, so this statement is true. The inconsistent results usually come from timing dependencies, shared mutable state, or reliance on unordered operations rather than from any change to the code or the test.

Why:

This is the defining characteristic of a flaky test: non-deterministic behavior where the same code under test and the same test code yield different outcomes across runs. The statement says exactly this, so it is true. The instability is typically caused by factors external to the code under test, such as timing dependencies, shared mutable state, or reliance on unordered operations.

Which of the following are common causes of flaky tests in an automated test suite? Select all that apply.#

Options

Pick every one that applies.

Show answer

Common causes of flaky tests include hard-coded sleeps that guess at timing, shared mutable state that makes tests order-dependent, and reliance on live external services. Each introduces variability, so the same test can pass and fail on identical code. Seeding random inputs reduces flakiness instead.

Why:

Hard-coded sleeps make results depend on machine load and scheduling, shared mutable state makes outcomes depend on the order tests run in, and live external services add network and availability variability. Pinning a seeded random generator does the opposite: it makes inputs deterministic and so reduces flakiness rather than causing it.

Name two common root causes of flaky test failures in an automated test suite.#

Show answer

Two common root causes of flaky test failures are: (1) shared state or test-order dependence, where one test modifies data another test relies on and only fails when run in a particular sequence; and (2) timing or synchronization issues, such as assertions that run before an async operation or UI element is ready, which the test handles with hardcoded sleeps instead of proper waits.

Why:

Flaky tests are non-deterministic: they pass or fail across runs without a code change. The two most frequently cited causes are shared mutable state (including test-order coupling, shared fixtures, or leftover data from earlier tests) and timing or synchronization problems (asserting before an asynchronous or UI action has settled). Either pair of these answers names two real, recurring root causes, which is why the question is open-ended and graded by keywords rather than a single keyed choice.

What is the term for a test that passes and fails for the same code and inputs, with no deterministic cause traceable to the code under test?#

Show answer

Flaky (a flaky test).

Why:

A flaky test is defined by its non-deterministic behavior: it passes and fails for the same code and inputs, with no deterministic cause traceable to the code under test. The term 'flaky' is the standard name for this property of a test.

A test that produces different pass/fail outcomes for the same code and inputs, with no code change explaining the variance, is called a _____ test.#

Show answer

A test that produces different pass/fail outcomes for the same code and inputs, with no code change explaining the variance, is called a flaky test.

Why:

The term 'flaky' describes a test whose pass/fail result is not deterministic for the same code and inputs. Such a test is named a flaky test, and the blank is filled with that single word.

An automated UI test intermittently fails with 'element not interactable' or 'stale element reference' errors. The failures do not reproduce on every run and are not tied to a code change. Which technique addresses the underlying race between the test and the application?#

Options

Show answer

Replacing fixed sleeps with explicit, condition-based waits, such as WebDriverWait with expected conditions, addresses the race behind intermittent 'element not interactable' and 'stale element reference' failures. The test blocks until the element is clickable, visible, or stale, so it no longer depends on machine speed or load. Retries and longer sleeps only hide the timing problem.

Why:

The errors come from the test acting before the element reaches the state it needs, which is a race between the test and the application. Explicit, condition-based waits, such as WebDriverWait with expected conditions for clickable, visible, or stale elements, block the test until the application reaches that state, so the same step succeeds regardless of machine speed or load. A fixed sleep guesses a duration and is fragile in both directions, and a retry hides the flakiness without removing the race. Pinning hardware does not fix the timing dependency and is not a real remedy.

An automated test suite has a test that passes on the developer's machine but fails roughly 20% of the time in CI. Name two common root causes that produce this intermittent pattern and briefly explain how each leads to non-deterministic results.#

Show answer

Two common causes are (1) shared mutable state between tests: when one test modifies data that another test depends on (database rows, in-memory caches, files, global config), the outcome depends on execution order and parallelism; and (2) timing or race conditions: when a test asserts before the application has finished an asynchronous operation, the assertion can pass or fail depending on thread scheduling, system load, or network latency. To diagnose shared state, run the failing test in isolation and in different orders to see whether it only fails after specific tests; to diagnose timing, replace fixed sleeps with explicit condition-based waits and log timing or screenshots on failure.

Why:

A test that passes locally but fails intermittently in CI is usually caused by environmental non-determinism rather than a logic error. Shared mutable state lets one test's side effects change another test's inputs, and CI's different ordering or parallel execution exposes dependencies that a sequential local run hides. Timing and race conditions occur when an assertion runs before an asynchronous operation such as a network call, render, or database write completes; slower, more loaded CI runners widen that window. Identifying which family is responsible is the first step toward a deterministic fix.

A test passes reliably when run alone but fails intermittently when run as part of the full test suite. You have already confirmed that it passes in isolation. Describe the predecessor-scan or bisection procedure you would use to find the single earlier test whose execution leaves shared mutable state that makes the failing test break.#

Show answer

Run the failing test immediately after each preceding test, one at a time, and note which predecessor makes it fail. Or bisect the test list: split the preceding tests in half, run the failing test after each half, keep the half that reproduces the failure, and repeat until one predecessor remains. Confirm the culprit by running just that predecessor followed by the failing test, and check that it leaves behind shared state such as a global, singleton, environment variable, database row, or file that the failing test depends on.

Why:

Once the test passes alone but fails in the full suite, the cause is order-dependence from shared mutable state left by an earlier test. The procedure is to run the failing test right after each preceding test one at a time, or to bisect the list by repeatedly running the failing test after each half and keeping the half that still reproduces the failure, until a single predecessor is isolated. A good answer also confirms the culprit by running that predecessor directly before the failing test and identifying the shared state it leaves behind.

An integration test passes reliably when run alone but fails intermittently when the full suite runs on CI. The test makes no network calls and runs against a fresh database container each time. Describe a diagnostic technique that would confirm the failure is caused by a test-ordering dependency on shared mutable state left behind by earlier tests.#

Show answer

Run the full suite repeatedly with test-order randomization (shuffle) enabled, recording the seed of each run. If the test fails only in orders where particular predecessor tests run before it, the failure depends on order. Then bisect the predecessor list, or run the failing test directly after each suspected predecessor, to isolate the minimal set of earlier tests that reliably reproduces the failure. Finally, confirm the mechanism by inspecting or resetting the shared state those predecessors touch (for example a singleton, cache, global config, or static field) and checking that the failure disappears when that state is reset between tests.

Why:

A test-ordering dependency is confirmed when its outcome changes with the set of tests executed before it, and when the failure can be reproduced deterministically by a specific predecessor sequence. Randomizing the order across repeated runs exposes whether failures track particular predecessors, and bisecting that predecessor list isolates the minimal set that reproduces the failure. Resetting or inspecting the shared in-process state those predecessors modify then verifies the mechanism. The fresh database container and absence of network calls rule out external sources of flakiness, leaving execution order and shared state as the variables under test.

Your team's UI test suite has a flaky test CheckoutFlow that fails about 15% of the time on CI with 'element not found' errors, but it never fails when run alone. The suite uses a shared browser session across tests. Describe three concrete diagnostic steps you would take to determine whether the flakiness is caused by test-ordering pollution (leftover DOM or browser state from earlier tests), and explain what each step tells you.#

Show answer
  1. Run CheckoutFlow in isolation 20+ times. If it never fails, the test itself is probably not inherently unstable, so the problem likely involves interactions with other tests. 2) Run the full suite with test-order randomization (shuffle) enabled across 5+ CI runs. If failures cluster when CheckoutFlow runs after specific tests, the flakiness depends on which tests ran before it, which points to leftover state from those tests. 3) Review CheckoutFlow and its neighboring tests for missing teardown, such as not navigating back to a clean page, not clearing localStorage or cookies, or not resetting the browser to a known state. This pinpoints the shared state that is not being cleaned up and the fix needed.
Why:

The three-step approach mirrors standard flaky-test diagnosis. First, running the test alone establishes whether it is inherently unstable; since it never fails in isolation, the cause is external to the test body. Second, shuffling the execution order across runs tests the ordering-dependency hypothesis: if failures correlate with specific predecessors, the flakiness is caused by state those tests leave behind. Third, reviewing the code for missing teardown identifies the specific shared state (DOM, cookies, localStorage, page location) that leaks between tests, which is what needs to be reset.

A test passes consistently when executed alone but fails intermittently when run as part of the full suite. All external dependencies are mocked, and the test uses explicit synchronization (no implicit waits). Which root cause does this symptom pattern indicate?#

Options

Show answer

Shared mutable state left behind by another test, a test-order dependency, is the root cause when a test passes alone but fails intermittently in the full suite. The flaky test implicitly relies on state, such as a database row or global variable, that a preceding test pollutes. External dependencies, explicit waits, and deterministic numeric errors do not explain this pattern.

Why:

The defining symptom, passing in isolation but failing in the suite, is the classic signature of a test-order dependency. An earlier test leaves shared mutable state (a database row, a global variable, a file, a singleton) in a condition the flaky test implicitly relies on. When the test runs alone that state is absent or default, so it passes; when a specific preceding test runs first, it pollutes the state and the test fails. A missing explicit wait is ruled out by the stated explicit-synchronization constraint, external API variability is ruled out by mocking, and floating-point errors are deterministic and would fail in isolation too, so none of those depend on interactions with other tests.

After confirming that a flaky test passes in isolation, you need to determine whether the flakiness is caused by test-order dependency (shared state from other tests) or by resource contention under concurrent execution. Describe the two separate experiments you would run and how you would interpret the results of each to distinguish the two causes.#

Show answer

Experiment 1 (order dependency): Run the full suite sequentially at a concurrency of one thread, in randomized order, across many iterations (for example 20 or more), each with a different shuffle seed. If failures cluster around specific orderings, such as the test consistently failing when it runs immediately after a particular other test, that points to shared mutable state between those tests. The fix is to isolate or reset that state in setup and teardown. Experiment 2 (resource contention): Keep the execution order fixed and run the suite at increasing concurrency levels (for example 1, 2, 4, and N threads or workers) while monitoring CPU, memory, and connection-pool usage. If the failure rate rises with thread count and the metrics show resource exhaustion, the cause is contention under parallel load. Because the first experiment varies ordering while holding concurrency fixed and the second varies concurrency while holding ordering fixed, the results separate the two causes cleanly.

Why:

The two causes have different triggers, so each needs its own controlled experiment. Order dependency is isolated by single-threaded runs with randomized order and a different seed per iteration; holding concurrency at one removes parallel load as a variable, so failures that cluster around specific predecessor tests reveal shared mutable state. Resource contention is isolated by varying the thread count while keeping the order fixed; holding order constant removes sequence as a variable, so failures that rise with concurrency and coincide with CPU, memory, or connection-pool exhaustion reveal contention. Since each experiment changes exactly one factor, the pattern of results in each identifies which cause is responsible.

A test passes reliably when executed alone but fails intermittently (~15% of full-suite runs) when the suite runs sequentially. Which root-cause hypotheses are consistent with this symptom pattern, and what diagnostic step would distinguish between them?#

Show answer

Two hypotheses fit this pattern: (1) order-dependent shared-state pollution, where an earlier test leaves residual state (database rows, globals, caches, uncleaned fixtures) that intermittently corrupts this test's environment; and (2) a timing or race-condition bug (for example un-awaited async work or contention on a shared resource) that only shows up under the load and scheduling of a full run. To distinguish them, rerun the full suite in the same order with per-test state isolation, giving each test a fresh database instance or a separate process. If the flake disappears, shared-state pollution is the likely cause; if it persists, a timing or async bug is more likely. Isolation also changes some timing, so treat the result as strong evidence rather than proof, and confirm by reproducing the failure with only the suspected polluting test run before the target test. A blanket full-state reset between every test is weaker evidence, because the reset itself changes timing and can mask a race just as it masks pollution.

Why:

The symptom (passes alone, flakes only in the full sequential suite) points to two families of cause: state left behind by earlier tests, and timing-dependent bugs that appear under full-suite load. The diagnostic that separates them is per-test state isolation (fresh database or separate process) run in the same order, because it removes cross-test state while keeping the suite's execution pattern. If the flake vanishes, pollution is the likely cause; if it persists, timing or async is more likely. A full reset between tests is not a clean test, since it alters timing and can hide a race and produce a false conclusion.

3#

Show answer

Three signal-to-cause mappings are valid: first-attempt failures that pass on retry suggest a warm-up or resource-initialization race; failure rates scaling with parallelism suggest shared mutable state or inter-test ordering dependencies; and constant failure rates independent of environment suggest genuine product-code nondeterminism. A 100% failure on one specific platform is deterministic, not flaky, so retrying it is the wrong response.

Why:

Three signal-to-cause mappings are correct. First-attempt failures that pass on retry, with no parallelism correlation, point to warm-up or resource-initialization race conditions in the test environment — the environment needs time to stabilize after initial resource allocation. Failure rates scaling with the number of concurrent test processes indicate contention over shared mutable state or implicit ordering dependencies between tests, because more parallelism increases the probability of interleaving. A constant failure rate invariant to parallelism, time of day, and execution duration points to genuine nondeterminism inside the product code itself, such as an application-level race condition, because no external environmental variable explains the variance. A test that fails 100% of the time on a specific OS/browser combination and never elsewhere is a deterministic compatibility defect, not a flaky test; quarantining and auto-retrying it masks a real bug rather than addressing intermittent nondeterminism, so that mapping is invalid.

Three signal-to-cause mappings are correct. First-attempt failures that pass on retry, with no parallelism correlation, point to warm-up or resource-initialization race conditions in the test environment. Failure rates scaling with concurrent test processes indicate shared mutable state or inter-test ordering dependencies. A constant failure rate invariant to all environmental variables points to genuine nondeterminism inside the product code itself.#

Show answer

Three signal-to-cause mappings are valid: first-attempt failures that pass on retry suggest a warm-up or resource-initialization race; failure rates scaling with parallelism suggest shared mutable state or inter-test ordering dependencies; and constant failure rates independent of environment suggest genuine product-code nondeterminism. A 100% failure on one specific platform is deterministic, not flaky, so retrying it is the wrong response.

Why:

Three signal-to-cause mappings are correct. First-attempt failures that pass on retry, with no parallelism correlation, point to warm-up or resource-initialization race conditions in the test environment — the environment needs time to stabilize after initial resource allocation. Failure rates scaling with the number of concurrent test processes indicate contention over shared mutable state or implicit ordering dependencies between tests, because more parallelism increases the probability of interleaving. A constant failure rate invariant to parallelism, time of day, and execution duration points to genuine nondeterminism inside the product code itself, such as an application-level race condition, because no external environmental variable explains the variance. A test that fails 100% of the time on a specific OS/browser combination and never elsewhere is a deterministic compatibility defect, not a flaky test; quarantining and auto-retrying it masks a real bug rather than addressing intermittent nondeterminism, so that mapping is invalid.

A test passes on developer machines but fails about 12% of the time in CI. It triggers a background job that updates a database row, then asserts the row was updated. You suspect the assertion reads the row before the job's write commits. Which diagnostic technique confirms whether the assertion is racing with the async job?#

Options

Show answer

Adding timestamped logs at the job trigger, just before the job's database commit, and just before the assertion confirms a race. Comparing their order on failing CI runs shows whether the assertion read the row before the async write landed. Retries can hide the symptom, and mocks change the system under test, so neither confirms the cause.

Why:

Timestamped logs at the trigger, the job's commit, and the assertion expose the real event ordering in the failing CI runs. If the assertion's log precedes the commit's log on a failing run, the test read the row before the async write landed, which directly confirms the race. A retry loop only hides the symptom and does not reveal ordering. Snapshotting updated_at is unreliable because the job's own write overwrites that field, so it yields no evidence about whether the write beat the assertion. Swapping in a synchronous mock changes the system under test and cannot confirm a race in the real database path.

In a test suite of 2000+ integration tests, one test fails intermittently in CI (about a 12% failure rate) but passes consistently on developer machines. Outline a systematic diagnostic process to identify the root cause. Specify at least two concrete signals or data points you would collect, and name at least one structural anti-pattern in test code that commonly causes flaky behavior.#

Show answer

First, rerun the suspect test 50 to 100 times in the same CI environment to reproduce the failure and confirm the flake rate, recording the exact failure mode (timeout, assertion mismatch, element-not-found) and how often each occurs. Collect two key signals: (1) the full stack trace and error message from each failure, which narrows the failure category, and (2) the test execution order, meaning the tests that ran immediately before the flaky test on failing runs versus passing runs. A strong correlation suggests test-ordering pollution from shared state that was not torn down between tests. Inspect the test code for structural anti-patterns: fixed-time sleep() or hardcoded timeouts used instead of condition-based polling, shared mutable state (global singletons, class-level mutable fields, database rows) not reset between runs, and dependence on external services with variable latency. Once a candidate root cause is identified, confirm it with a minimal reproduction, such as adding a deliberate delay before the assertion or removing the cleanup step, that turns the intermittent failure into a deterministic one. That proves causation rather than mere correlation.

Why:

A sound answer reproduces the flake many times in the failing environment to measure its rate and failure mode, collects at least two signals (such as the stack trace or error type and the preceding test execution order), names a structural anti-pattern such as fixed sleeps, shared mutable state without teardown, or uncontrolled external dependencies, and closes with a minimal reproduction that makes the failure deterministic, which proves causation rather than correlation.

A Jest test intermittently fails in CI when the full suite runs with --maxWorkers=4. It passes reliably when run alone (--testNamePattern), when the full suite runs with --runInBand (a single worker), and across the last 50 local runs. The failing test reads a JSON fixture from a hardcoded path, /tmp/shared-fixture.json. A separate test in the same suite creates, populates, and deletes /tmp/shared-fixture.json in its own beforeEach/afterEach hooks. The failing test has no database, no network, and no other file dependencies. What explains the intermittent CI failure?#

Show answer

With --maxWorkers=4, Jest runs test files in four parallel worker processes that share the same filesystem. The failing test reads /tmp/shared-fixture.json at a hardcoded path while a test file running in a sibling worker creates and deletes that same file in its hooks. This is a race condition: the reader hits a missing, partially written, or stale file intermittently. The test passes in isolation and with --runInBand because no concurrent worker touches the fixture during its read. The underlying cause is test interference through shared filesystem state at a fixed path; the tests are not independent because they both use the same /tmp file without coordination. A fix is to give each worker or test its own unique temp directory (for example, via fs.mkdtemp or Jest's per-worker identifiers) instead of a fixed path.

Why:

The diagnostic pattern (passes alone, passes single-worker, passes locally, flakes only with several workers) isolates the variable to concurrent worker processes. Nothing internal to the failing test changes between passing and failing runs, and it has no external dependencies besides the file. The failing test reads a fixed path that a separate test creates and deletes in its hooks, so when a sibling worker runs that other test at the same moment, the reader can find the file missing or in an unexpected state. The answer is shared filesystem state at a fixed path accessed by parallel workers, i.e. a race between tests that are not independent. Isolating the path per worker or per test removes the race.

A Jest test in your CI pipeline fails intermittently. It passes on some runs and fails on others, with no code change between them. Describe the diagnostic techniques you would use to find the root cause of the flakiness. Then explain why adding a retry or a larger timeout is not a valid diagnostic approach.#

Show answer

First, isolate the test: run it alone with --testNamePattern or by running only its file. If it passes alone but fails in the full suite, another test is likely leaking state (shared globals, mocks not reset, database rows, or module-level caches). Second, run the suite serially with --runInBand to remove parallel-worker interference; if the failure disappears or changes, the cause is concurrency or shared resources. Third, reproduce the failure deterministically by looping the test many times locally, so the intermittent failure can be debugged with logs and a debugger. Fourth, use git bisect over the commit history to find the change that introduced the flake. Adding retries or a larger timeout is not diagnosis: it brute-forces the test to pass and hides the non-determinism without revealing why it fails. The flake remains in the codebase, and it can get worse, so the fix must address the underlying cause, such as a race condition, a missing await, or leaked state.

Why:

A strong answer names concrete diagnostic techniques that expose the cause of non-determinism: isolating the test to detect order dependence or state leaks, running serially with --runInBand to rule out parallel-worker interference, looping the test to reproduce the failure, and using git bisect to locate the introducing commit. It must also explain that retries or larger timeouts are not diagnostics because they mask the symptom, keep the underlying non-determinism in the codebase, and do not identify why the test fails. The question asks for an open description and justification, so no single option is correct and it stays a short-answer question graded by keywords and the rubric in the sample answer.

A test passes consistently on your machine but fails intermittently in CI. Describe two concrete techniques you would use to isolate the root cause of the flaky test, and state what each technique would reveal about the failure.#

Show answer

First, run the test repeatedly in isolation (for example, a loop of 50+ iterations) to reproduce the flake locally. If it fails non-deterministically when run alone, the cause is likely a race condition or timing dependency inside the test or the code under test. Second, run the full suite in randomized order, or with the framework's seed/shuffle option, to detect test-order dependencies. If reordering reproduces the failure, one test is leaving shared mutable state or inadequate cleanup that pollutes another test. Additional techniques include enabling verbose logging or adding assertions around critical shared resources to capture interleaving, and disabling retry-on-failure in CI to confirm the failure is genuinely transient rather than masked by retries.

Why:

The question asks for concrete diagnostic techniques for flaky tests, so a correct answer must name at least one method that actively surfaces non-determinism, such as running the test many times in isolation to reproduce timing-dependent failures, or randomizing test order to expose state pollution between tests. Each technique should also state the failure mode it reveals: repeated isolated runs point to races or timing dependencies, while shuffled ordering points to shared mutable state or missing cleanup. Verbose logging and disabling CI retries are complementary because they capture the interleaving behind the flake and confirm whether the failure is genuinely transient. The sample answer covers repeated isolated execution, randomized ordering, and logging, each paired with the specific failure mode it reveals.

You are diagnosing a flaky test (Test T) in a CI pipeline that runs 500 tests across 8 parallel workers sharing a database connection pool. Over 500 CI runs (two weeks of builds), Test T fails in 50 runs (10%), always with a 'connection is in a transaction' error. In 48 of those 50 failing runs, Test T was the first test scheduled on a worker immediately after a connection was recycled from another test that had opened but not rolled back a transaction. In the other 2 failing runs, the same error occurred but the prior test could not be identified from the logs. In the 450 passing runs, Test T either used a freshly created connection or was preceded by tests that properly rolled back their transactions. Test T does not check or reset transaction state before running its queries; it assumes the connection is in autocommit mode. When run in isolation with a fresh connection, Test T passes 100% of the time over 200 runs. What is the root cause of Test T's flakiness?#

Show answer

Test T's flakiness is caused by shared-connection state pollution: another test leaves a transaction open on a pooled connection without rolling it back, and when that connection is recycled to Test T, Test T runs its queries in a non-autocommit state it never checks or resets. The root cause is the other test's incomplete cleanup combined with Test T's unverified assumption about connection state, not a timeout, pool exhaustion, or a race in Test T itself, since Test T passes in isolation on a fresh connection.

Why:

The evidence points to shared-connection state pollution. In 48 of 50 failures, Test T was the first test to receive a connection that another test had recycled while still holding an open, uncommitted transaction. Test T assumes autocommit mode and never verifies or resets connection state, so it inherits the dirty state and hits the 'connection is in a transaction' error. This also explains why it passes in isolation, where it always gets a fresh connection, and why it passes in CI when preceded by tests that roll back properly. A race in Test T's own teardown would reproduce in isolation, which it does not, and pool exhaustion or a short timeout would not produce a transaction-state error.

A flaky test in your CI suite fails with a 'connection is in a transaction' error in 10% of runs. Data shows that 48 of 50 failures occur when the test is the first to use a recycled database connection previously left in an open-transaction state by another test. The test itself assumes autocommit and passes 100% of 200 isolated runs. This pattern is a classic violation of test ___ — the test does not defensively initialize its own connection state and is victimized by another test's incomplete cleanup through shared infrastructure.#

Show answer

isolation

Why:

This scenario is a textbook test-isolation violation. The test does not control or reset its initial conditions — specifically the transaction state of its database connection — and is therefore vulnerable to pollution from other tests that share the same connection pool. Proper test isolation requires each test to set up and tear down its own state defensively, including verifying connection state, rather than assuming clean infrastructure.

In flaky-test diagnosis, if a test passes reliably when run alone but flakes only when run alongside other tests in the suite, the likely explanation is a violation of test _____ rather than a bug in the code under test.#

Show answer

In flaky-test diagnosis, if a test passes reliably when run alone but flakes only when run alongside other tests in the suite, the likely explanation is a violation of test isolation rather than a bug in the code under test.

Why:

The variable that changes between the two runs is the presence of other tests, so the flakiness comes from the execution context rather than from the production code's logic. This points to shared mutable state (database rows, global variables, file system artifacts, or environment variables) left dirty by a prior test, which is a breach of test isolation (independence). A genuine production race condition is inherent to the code's concurrency logic and would typically reproduce when the test runs alone too.

A flaky-test detection pipeline runs each test 10 times on a clean commit (no code changes) and flags any test that produces at least one pass and at least one failure across those 10 runs. For a test with a true per-run failure probability of p = 0.05, independent across runs, what is the approximate probability that this test escapes detection as flaky? Give the value and briefly justify it.#

Show answer

The test escapes detection only if all 10 runs produce the same outcome. The all-pass case dominates: P(all 10 pass) = (1 − 0.05)^10 = 0.95^10 ≈ 0.599. The all-fail case, 0.05^10 ≈ 10^-13, is negligible. So the escape probability is approximately 60%, meaning a 10-run detector misses the majority of tests with a 5% per-run flake rate. This is why detection pipelines should scale run counts adaptively or combine repeated runs with static analysis of non-determinism sources such as shared state, time dependence, network calls, and random seeds.

Why:

The test escapes detection only when all 10 runs yield the same outcome, either all pass or all fail. Because runs are independent with per-run failure probability 0.05, P(all 10 pass) = 0.95^10 ≈ 0.599, which dominates. P(all 10 fail) = 0.05^10 ≈ 9.8 × 10^-14 is negligible. The escape probability is therefore approximately 60%, so a fixed 10-run detector misses most tests with a 5% true flake rate.

Related interview questions

Job market

See test-automation salaries and hiring demand from live job postings.

Practise these until they stick

That's every question we hold on this topic, and the page marks what you pick. What it can't do is remember. A free account keeps every answer, and what you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 marked answers per 30 days · written feedback on the paid plan

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.