Test Data Management
Manage Selenium test data at scale: builders and factories, unique data for parallel runs, API seeding, reliable cleanup, config, secrets and faker libs.
Ask a team why their UI suite is flaky and you will hear about waits and locators. Look at the failures and a surprising share are data problems: a test that expects user testuser1 to have an empty cart, but another test added an item; an order number hard-coded months ago that has since been archived; two parallel workers creating a customer with the same email and one of them hitting a uniqueness error.
Good test data management makes every test own the data it depends on: it creates what it needs, uses values nobody else uses, and cleans up afterwards. This lesson covers the patterns that make that practical.
Principles
- Each test creates its own data. Shared fixtures that many tests read and some tests modify are the root of order-dependent failures.
- Data is unique per run and per worker. Parallel tests must never collide on emails, usernames or order references.
- Set up through the fastest reliable channel. Use the UI for the behaviour under test, and APIs or database seeding for everything else.
- Clean up, but do not depend on cleanup. Tests must pass even if a previous run’s cleanup failed.
- Defaults live in one place. A test states only the fields it cares about; everything else comes from a factory.
- Secrets never live in source code.
Builders and Factories
Writing new User("Ada", "Lovelace", "ada@example.com", "Passw0rd!", "GB", true, ...) in every test makes tests noisy and brittle: add a required field and you touch 200 call sites. A factory produces valid objects with sensible defaults; a builder lets each test override only what matters.
public record User(String firstName, String lastName, String email, String password, String country, boolean verified) {}
public class UserBuilder { private static final Faker faker = new Faker(); // net.datafaker.Faker
private String firstName = faker.name().firstName(); private String lastName = faker.name().lastName(); private String email = UniqueData.email("user"); private String password = UniqueData.password(); private String country = "GB"; private boolean verified = true;
public static UserBuilder aUser() { return new UserBuilder(); }
public UserBuilder withCountry(String country) { this.country = country; return this; } public UserBuilder unverified() { this.verified = false; return this; } public UserBuilder withEmail(String email) { this.email = email; return this; }
public User build() { return new User(firstName, lastName, email, password, country, verified); }}
// Tests state only what matters to themUser user = aUser().withCountry("DE").unverified().build();from dataclasses import dataclass, fieldfrom faker import Faker
fake = Faker()
@dataclassclass User: first_name: str = field(default_factory=fake.first_name) last_name: str = field(default_factory=fake.last_name) email: str = field(default_factory=lambda: unique_email("user")) password: str = field(default_factory=unique_password) country: str = "GB" verified: bool = True
# Dataclass defaults act as the factory; keyword args are the builderuser = User(country="DE", verified=False)const { faker } = require('@faker-js/faker');
function aUser(overrides = {}) {return { firstName: faker.person.firstName(), lastName: faker.person.lastName(), email: uniqueEmail('user'), password: uniquePassword(), country: 'GB', verified: true, ...overrides,};}
// Tests state only what matters to themconst user = aUser({ country: 'DE', verified: false });using Bogus;
public record User(string FirstName, string LastName, string Email, string Password, string Country, bool Verified);
public static class Users{ private static readonly Faker Fake = new();
public static User AUser( string? country = null, bool verified = true, string? email = null) => new( Fake.Name.FirstName(), Fake.Name.LastName(), email ?? UniqueData.Email("user"), UniqueData.Password(), country ?? "GB", verified);}
// Tests state only what matters to themvar user = Users.AUser(country: "DE", verified: false);Defaults should always produce a valid object. A test that wants an invalid value (an email without @, a password that is too short) overrides that one field, which makes the test’s intent obvious when reading it.
Unique Data for Parallel Runs
Random-looking data from a faker library is not the same as unique data. faker.name().firstName() will collide eventually, and across thousands of runs, “eventually” is next Tuesday. For fields that must be unique (emails, usernames, external references), build values from things that are guaranteed distinct: a run ID, the worker ID, and a counter or UUID.
public final class UniqueData { private static final String RUN_ID = Optional.ofNullable(System.getenv("CI_PIPELINE_ID")).orElse("local"); private static final AtomicLong COUNTER = new AtomicLong();
public static String suffix() { return RUN_ID + "-" + ProcessHandle.current().pid() + "-" + COUNTER.incrementAndGet(); }
public static String email(String prefix) { // Plus-addressing lets one real mailbox receive all test mail if needed return prefix + "+" + suffix() + "@test.example.com"; }
public static String password() { return "T3st!" + UUID.randomUUID().toString().substring(0, 12); }}import itertools, os, uuid
RUN_ID = os.getenv("CI_PIPELINE_ID", "local")WORKER = os.getenv("PYTEST_XDIST_WORKER", "w0")_counter = itertools.count(1)
def suffix() -> str: return f"{RUN_ID}-{WORKER}-{next(_counter)}"
def unique_email(prefix: str) -> str: # Plus-addressing lets one real mailbox receive all test mail if needed return f"{prefix}+{suffix()}@test.example.com"
def unique_password() -> str: return "T3st!" + uuid.uuid4().hex[:12]const crypto = require('crypto');
const RUN_ID = process.env.CI_PIPELINE_ID || 'local';const WORKER = process.env.JEST_WORKER_ID || process.env.MOCHA_WORKER_ID || String(process.pid);let counter = 0;
function suffix() {counter += 1;return RUN_ID + '-' + WORKER + '-' + counter;}
function uniqueEmail(prefix) {// Plus-addressing lets one real mailbox receive all test mail if neededreturn prefix + '+' + suffix() + '@test.example.com';}
function uniquePassword() {return 'T3st!' + crypto.randomUUID().slice(0, 12);}public static class UniqueData{ private static readonly string RunId = Environment.GetEnvironmentVariable("CI_PIPELINE_ID") ?? "local"; private static long _counter;
public static string Suffix() => $"{RunId}-{Environment.ProcessId}-{Interlocked.Increment(ref _counter)}";
// Plus-addressing lets one real mailbox receive all test mail if needed public static string Email(string prefix) => $"{prefix}+{Suffix()}@test.example.com";
public static string Password() => "T3st!" + Guid.NewGuid().ToString("N")[..12];}The run ID makes data traceable: when you find user+4821-gw2-17@test.example.com in a staging database, you know which pipeline created it. It also makes bulk cleanup possible (“delete everything created by runs older than a day”).
Use reserved domains for test emails: example.com, example.org, or a domain your organisation owns and routes to a test mail catcher. Never generate emails at real providers; a random @gmail.com address may belong to a real person.
Tip: Seed your faker with a fixed value when you need reproducibility (debugging a failure that only occurs with certain names or lengths), and log the seed on every run. Most faker libraries accept a seed: Datafaker via
new Faker(new Random(seed)), PythonFaker.seed(seed),faker.seed(seed)in JavaScript, andRandomizer.Seed = new Random(seed)in Bogus.
Seeding Through the API, Not the UI
If a test is about “a customer can cancel an order”, creating the customer, logging in, adding products, checking out and only then reaching the cancel button through the UI wastes minutes and exercises five features that have their own tests. Worse, a bug in checkout fails the cancel test, which misdirects the investigation.
Create the preconditions through the application’s API, then use the browser only for the behaviour under test.
// Arrange: fast and independent of the UIUser user = aUser().build();ApiClient api = ApiClient.forEnvironment(config);String userId = api.createUser(user);String orderId = api.createOrder(userId, List.of("SKU-123", "SKU-456"));String sessionToken = api.login(user.email(), user.password());
// Reuse the API session in the browser instead of logging in via the formdriver.get(config.baseUrl() + "/favicon.ico"); // set cookies on the right domain firstdriver.manage().addCookie(new Cookie("session", sessionToken));
// Act + assert: only the behaviour under test goes through the browserdriver.get(config.baseUrl() + "/orders/" + orderId);new OrderPage(driver).cancel().confirm();assertEquals("Cancelled", new OrderPage(driver).status());# Arrange: fast and independent of the UIuser = User()api = ApiClient.for_environment(config)user_id = api.create_user(user)order_id = api.create_order(user_id, ["SKU-123", "SKU-456"])token = api.login(user.email, user.password)
# Reuse the API session in the browser instead of logging in via the formdriver.get(f"{config.base_url}/favicon.ico") # set cookies on the right domain firstdriver.add_cookie({"name": "session", "value": token})
# Act + assert: only the behaviour under test goes through the browserdriver.get(f"{config.base_url}/orders/{order_id}")OrderPage(driver).cancel().confirm()assert OrderPage(driver).status == "Cancelled"// Arrange: fast and independent of the UIconst user = aUser();const api = ApiClient.forEnvironment(config);const userId = await api.createUser(user);const orderId = await api.createOrder(userId, ['SKU-123', 'SKU-456']);const token = await api.login(user.email, user.password);
// Reuse the API session in the browser instead of logging in via the formawait driver.get(config.baseUrl + '/favicon.ico'); // set cookies on the right domain firstawait driver.manage().addCookie({ name: 'session', value: token });
// Act + assert: only the behaviour under test goes through the browserawait driver.get(config.baseUrl + '/orders/' + orderId);await (await new OrderPage(driver).cancel()).confirm();assert.strictEqual(await new OrderPage(driver).status(), 'Cancelled');// Arrange: fast and independent of the UIvar user = Users.AUser();var api = ApiClient.ForEnvironment(config);var userId = await api.CreateUserAsync(user);var orderId = await api.CreateOrderAsync(userId, new[] { "SKU-123", "SKU-456" });var token = await api.LoginAsync(user.Email, user.Password);
// Reuse the API session in the browser instead of logging in via the formdriver.Navigate().GoToUrl($"{config.BaseUrl}/favicon.ico"); // set cookies on the right domain firstdriver.Manage().Cookies.AddCookie(new Cookie("session", token));
// Act + assert: only the behaviour under test goes through the browserdriver.Navigate().GoToUrl($"{config.BaseUrl}/orders/{orderId}");new OrderPage(driver).Cancel().Confirm();Assert.That(new OrderPage(driver).Status, Is.EqualTo("Cancelled"));Keep one honest end-to-end test per critical journey (sign-up, checkout) that goes through the UI from start to finish. Everything else seeds via API. Cookie injection details are covered in Cookies and Storage.
Seeding options compared
| Approach | Speed | Realism | Coupling | Notes |
|---|---|---|---|---|
| UI setup | Slowest | Highest | To the UI | Reserve for the behaviour under test |
| Public/internal API | Fast | High; goes through business rules | To API contracts | Best default |
Test-only endpoints (/test/seed) | Fastest | Medium | To a test hook | Must be disabled in production |
| Direct database inserts | Fast | Low; bypasses validation | To the schema | Breaks on migrations; last resort |
| Database snapshot/restore | Fast per test after setup | Depends on snapshot | To the snapshot | Good for ephemeral environments |
Cleanup That Does Not Break Tests
Every test that creates data should try to delete it. A simple, robust pattern is a per-test registry of cleanup actions that runs in reverse order after the test, whether it passed or failed.
public class TestDataTracker implements AutoCloseable { private final Deque<Runnable> cleanups = new ArrayDeque<>();
public <T> T track(T created, Runnable cleanup) { cleanups.push(cleanup); return created; }
@Override public void close() { while (!cleanups.isEmpty()) { try { cleanups.pop().run(); } catch (RuntimeException e) { // Log and continue: cleanup failures must not fail the test or skip other cleanups System.err.println("Cleanup failed: " + e.getMessage()); } } }}
// JUnit 5private final TestDataTracker data = new TestDataTracker();
@AfterEachvoid cleanUp() { data.close(); }
@Testvoid cancelOrder() { String userId = api.createUser(aUser().build()); data.track(userId, () -> api.deleteUser(userId));
String orderId = api.createOrder(userId, List.of("SKU-123")); data.track(orderId, () -> api.deleteOrder(orderId)); // ...}import pytest
@pytest.fixturedef cleanup(): actions = [] yield actions.append for action in reversed(actions): try: action() except Exception as e: # log and continue print(f"Cleanup failed: {e}")
def test_cancel_order(driver, api, cleanup): user = User() user_id = api.create_user(user) cleanup(lambda: api.delete_user(user_id))
order_id = api.create_order(user_id, ["SKU-123"]) cleanup(lambda: api.delete_order(order_id)) # ...// Mocha / Jest stylelet cleanups = [];const track = (fn) => cleanups.push(fn);
afterEach(async () => {for (const fn of cleanups.reverse()) { try { await fn(); } catch (e) { console.warn('Cleanup failed:', e.message); }}cleanups = [];});
it('cancels an order', async () => {const userId = await api.createUser(aUser());track(() => api.deleteUser(userId));
const orderId = await api.createOrder(userId, ['SKU-123']);track(() => api.deleteOrder(orderId));// ...});public class TestDataTracker : IAsyncDisposable{ private readonly Stack<Func<Task>> _cleanups = new();
public void Track(Func<Task> cleanup) => _cleanups.Push(cleanup);
public async ValueTask DisposeAsync() { while (_cleanups.TryPop(out var cleanup)) { try { await cleanup(); } catch (Exception e) { TestContext.WriteLine($"Cleanup failed: {e.Message}"); } } }}
// NUnitprivate TestDataTracker _data = null!;
[SetUp] public void SetUp() => _data = new TestDataTracker();[TearDown] public async Task TearDown() => await _data.DisposeAsync();
[Test]public async Task CancelOrder(){ var userId = await api.CreateUserAsync(Users.AUser()); _data.Track(() => api.DeleteUserAsync(userId)); // ...}Reverse order matters: delete the order before the user that owns it, or foreign keys reject the deletion. Catching and logging inside the loop matters too: one failing cleanup must not skip the rest or mask the real test result.
Even with careful cleanup, data will leak (killed CI jobs, crashed runners). Add a scheduled sweeper that deletes anything matching your test-data pattern older than a day. Because unique values carry the run ID and a recognisable prefix, the sweeper can find them safely.
Warning: Never point cleanup code at a production environment. Guard destructive helpers with an explicit environment check (for example, refuse to run if the base URL matches the production domain). One misconfigured environment variable should not be able to delete real customer data.
Environment Configuration
The same suite runs locally, against a dev environment, in CI against staging, and possibly as a smoke test against production. Hard-coded URLs and accounts make that impossible. Externalise everything that differs between environments and load it once.
baseUrl: https://staging.example.comapiUrl: https://api.staging.example.combrowser: chrometimeouts: explicitSeconds: 10features: newCheckout: trueLoad the file based on a single environment variable (TEST_ENV=staging), and let individual environment variables override any value. That layering (defaults, then environment file, then environment variables) keeps CI configuration small and lets developers point a local run at any environment without editing files.
public record TestConfig(String baseUrl, String apiUrl, String browser) { public static TestConfig load() { String env = System.getenv().getOrDefault("TEST_ENV", "local"); Map<String, Object> file = Yaml.load(Path.of("config", env + ".yaml")); // e.g. SnakeYAML/Jackson
return new TestConfig( override("BASE_URL", (String) file.get("baseUrl")), override("API_URL", (String) file.get("apiUrl")), override("BROWSER", (String) file.get("browser"))); }
private static String override(String envVar, String fallback) { return Optional.ofNullable(System.getenv(envVar)).orElse(fallback); }}import osfrom dataclasses import dataclassimport yaml
@dataclass(frozen=True)class TestConfig: base_url: str api_url: str browser: str
@classmethod def load(cls): env = os.getenv("TEST_ENV", "local") with open(f"config/{env}.yaml") as f: file = yaml.safe_load(f) return cls( base_url=os.getenv("BASE_URL", file["baseUrl"]), api_url=os.getenv("API_URL", file["apiUrl"]), browser=os.getenv("BROWSER", file["browser"]), )const fs = require('fs');const yaml = require('yaml');
function loadConfig() {const env = process.env.TEST_ENV || 'local';const file = yaml.parse(fs.readFileSync('config/' + env + '.yaml', 'utf8'));return Object.freeze({ baseUrl: process.env.BASE_URL || file.baseUrl, apiUrl: process.env.API_URL || file.apiUrl, browser: process.env.BROWSER || file.browser,});}// Microsoft.Extensions.Configuration does the layering for youvar env = Environment.GetEnvironmentVariable("TEST_ENV") ?? "local";
var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env}.json", optional: true) .AddEnvironmentVariables() // BASEURL, APIURL, ... override files .Build();
var config = configuration.Get<TestConfig>()!;Choosing the browser from configuration is covered in the browser from environment recipe.
Handling Secrets
Test accounts, API keys and service tokens are real credentials. Leaked staging credentials have been the entry point for plenty of real incidents.
- Never commit secrets, including in config files “just for staging”. Add config files containing secrets to
.gitignore, and run a secret scanner (gitleaks, GitHub secret scanning, trufflehog) in CI. - Inject secrets as environment variables from the CI system’s secret store (GitHub Actions secrets, GitLab CI variables, Azure Key Vault, AWS Secrets Manager, HashiCorp Vault).
- Mask them in logs. CI systems mask registered secrets automatically, but your own logging may not. Do not log full request bodies containing passwords or tokens, and redact
Authorizationheaders. - Keep them out of reports and screenshots. Typing a password into a field that is briefly visible as plain text, or a report that prints the test’s parameters, can leak it. Prefer API-based login (cookie injection) over typing passwords where possible.
- Use least-privilege, test-only accounts that can be rotated without affecting anything else.
- Rotate after exposure. If a secret ever lands in git history, removing the commit is not enough; rotate it.
For local development, a gitignored .env file loaded at startup (dotenv libraries exist for every language) keeps developers productive without putting secrets in the repository.
Faker Libraries by Language
| Language | Library | Package |
|---|---|---|
| Java | Datafaker (maintained successor to java-faker) | net.datafaker:datafaker |
| Python | Faker | faker |
| JavaScript/TypeScript | Faker | @faker-js/faker |
| C#/.NET | Bogus | Bogus |
All four support locales (de_DE, ja_JP…), which is worth using deliberately: names with accents, long surnames and non-Latin scripts catch real rendering and validation bugs. Use them for realistic variety, and use the unique-data helpers for anything that must not collide.
Static Data Sets and Reference Data
Not everything should be generated. Reference data (countries, currencies, product catalogue entries, feature-flag states) is often better as known, versioned data:
- Store it as files in the repository (JSON, YAML, CSV) and load it in data-driven tests; see Data-Driven Testing.
- Seed it into ephemeral environments as part of environment creation, not per test.
- Treat it as read-only in tests. A test that needs a modified product creates its own product.
Common Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| Test passes alone, fails in the suite | Shared mutable data | Each test creates its own data |
| “Email already exists” in parallel runs | Non-unique values | Run ID + worker ID + counter |
| Tests break after a schema change | Direct DB inserts | Seed through the API |
| Staging fills with junk data | No cleanup, or cleanup skipped on failure | Tracker with reverse-order cleanup plus a sweeper |
| Suite cannot run against another environment | Hard-coded URLs and accounts | Layered configuration |
| Credentials in git history | Secrets in config files | Environment variables from a secret store; rotate |
| Five-minute setup for a ten-second check | UI-based setup | API seeding and cookie injection |
Summary
- Make every test own its data: create it, keep it unique, clean it up.
- Use builders/factories so tests specify only what matters.
- Generate uniqueness from run, worker and counter; use faker libraries for realism.
- Seed through APIs and inject sessions; keep the browser for the behaviour under test.
- Configure environments in layers and keep secrets in a secret store, never in the repository.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.