Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Hooks and Tags

Test Data Setup and Cleanup

Manage test data in Cucumber suites: Given steps versus hooks, data builders, unique values, rollback and cleanup strategies, and keeping scenarios independent.

Most flaky test suites are not flaky because of timing. They are flaky because scenarios share data. One scenario creates a user called alice, another expects that no user called alice exists, and the result depends on which one runs first. This lesson gives you a toolbox for data that keeps every scenario independent: it should pass alone, in any order, and in parallel with others.

We will separate business data that belongs in the Gherkin from technical data that belongs in code, build test data with builders, choose a cleanup strategy and keep unique values unique. The real database and frameworks are not available here, so the Java examples are in-memory stand-ins that you can run.

Business data goes in Given steps

If the behavior depends on a fact, show the fact:

GHERKIN
Scenario: Gold customers get free shipping
  Given a customer "Mina" with a gold membership
  And a cart worth 20 dollars
  When she checks out
  Then shipping costs 0 dollars

Do not hide "gold membership" in a @Before hook or in a SQL script that the reader never sees. A hook is the place for technical facts such as "the database is empty" or "the clock is frozen at noon". The rule of thumb: if changing the value would change the expected result, it must be visible in the scenario.

Details that do not matter should not appear. "A customer" is better than "a customer with first name John, last name Smith, email [email protected], birthday...". Fill the unimportant fields with sensible defaults inside a builder.

Builders for test data

A test data builder creates a valid object with defaults, and lets a step override only the fields the scenario cares about.

Java A customer builder with defaults (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The step definition then reads naturally:

Java
@Given("a customer {string} with a {word} membership")
public void customer(String name, String membership) {
    world.customer = customers.save(
        new CustomerBuilder().named(name).withMembership(membership).build());
}

Keeping values unique

If your system enforces unique emails or usernames, a fixed value like [email protected] will fail the second time it is created, in a different scenario, or in a parallel worker. Strategies:

  • Generate a suffix: "alice-" + UUID.randomUUID(), or a counter that is safe across threads (AtomicInteger).
  • Keep the display name from the Gherkin (Mina) separate from the unique key ([email protected]). Steps look up the object by its display name through the world, not through the database.
  • Use a per-run prefix, so you can find and delete all data created by one run.

Cleanup strategies

Strategy How Good for Watch out
Transaction rollback open a transaction in @Before, roll back in @After service-level and repository tests in one process does not work if the app under test uses its own connection, such as a UI test against a server
Truncate or delete clear tables in @Before or @After integration tests with a local database order of deletes (foreign keys), speed
Fresh database container or in-memory database per run or per worker parallel suites start-up cost
Own your data each scenario creates data with unique keys and deletes it in @After shared test environments cleanup must run even after failures (it does: @After always runs, see Hooks)
Reset through the API call an admin or test-only endpoint UI suites protect that endpoint in production

Clean up before a scenario if you can, not only after. A crashed earlier run, or a debugging session that stopped halfway, leaves dirt that an @After hook never saw. Starting clean makes the suite self-healing.

This stand-in keeps a fake database, wraps each scenario in a snapshot, and restores the snapshot afterwards, the same idea as a rolled-back transaction.

Java Rollback after each scenario (Java stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each scenario sees only its own row, and the final database is exactly the baseline.

Reference data versus scenario data

Some data never changes during tests: countries, currencies, product categories. Load it once in @BeforeAll or at database start-up and treat it as read-only. Data that a scenario changes or creates is scenario data and must be isolated with the strategies above. Mixing the two is a common source of "works on my machine".

Time is also data. If a rule depends on "today", control the clock: inject a Clock you can set (Given today is 2026-12-24) instead of calling LocalDate.now() inside the code under test.

Common mistakes

  • Sharing one big "golden" database dump that every scenario edits.
  • Hardcoded ids in Gherkin (customer 42), which break when seed data changes.
  • Cleanup written only for the passing path.
  • A Background that creates ten records most scenarios never use; keep Backgrounds small.
  • Hiding business-relevant data in SQL files. See Declarative scenarios for what belongs in Gherkin.

Next you will use the page object pattern to keep UI details out of step definitions too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the fact 'the customer has a gold membership' appear when the expected shipping price depends on it?

    If the data changes the outcome, readers must see it in the scenario text.
  2. 2. What problem does a fixed email like [email protected] cause in a suite with a unique-email rule?

    Unique constraints reject duplicates, so shared fixed values make scenarios depend on each other.
  3. 3. Why clean up before a scenario as well as after?

    Starting clean makes the suite self-healing after aborted runs.
  4. 4. Which cleanup strategy fails when a UI test talks to a separate server process?

    The server uses its own connection, so the test's transaction does not cover the data it writes.

Summary

  • Show business-relevant data in Given steps; keep technical setup in hooks.
  • Use builders with defaults so scenarios mention only what matters.
  • Make unique values unique, and keep display names apart from keys.
  • Pick a cleanup strategy (rollback, truncate, fresh database, own-your-data) and clean before as well as after.
  • Treat reference data as read-only and control the clock.

Next: The page object pattern