Q21 of 26 · SQL

How do you verify that test teardown actually cleaned up all test data?

SQLSeniorsqlteardowncleanuptest-isolationassertions

Short answer

Short answer: After teardown runs, query each table using the test-data identifier (ID range, email prefix, run ID) and assert COUNT(*) = 0. Automate this as a post-suite assertion, not a manual check.

Detail

Teardown that silently fails leaves pollution that causes future test failures in confusing ways. The verification pattern:

-- After teardown, confirm all test data is gone
SELECT COUNT(*) AS leftover_users
FROM   users
WHERE  email LIKE 'test-%@example.com';
-- Assert = 0

SELECT COUNT(*) AS leftover_orders
FROM   orders
WHERE  customer_id IN (
  SELECT id FROM users WHERE email LIKE 'test-%@example.com'
);
-- Assert = 0 (or this table was also cleaned)

In a test framework (e.g., Java + JDBC):

@AfterEach
void verifyCleanup() {
  int remaining = db.queryForObject(
    "SELECT COUNT(*) FROM users WHERE email LIKE 'test-%'", Integer.class);
  assertThat(remaining).isZero();
}

Cascade verification — if your app deletes a parent and relies on CASCADE, verify child tables too:

SELECT COUNT(*) FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE o.customer_id = :test_customer_id;
-- Should be 0 if CASCADE DELETE is working

Why this matters: Teardown failures compound — each failed cleanup adds more noise, until a test that used to take 2 minutes runs for 20 because it's filtering through thousands of stale rows.

// WHAT INTERVIEWERS LOOK FOR

Post-teardown assertion as an automated check, not trust. CASCADE verification. Understanding the compounding failure mode of silent teardown failures.