Realistic test data with Java Faker
Reliable automated tests need data that behaves like production without carrying production risk. Fixed names and addresses can conceal formatting, encoding, and uniqueness defects, while copied customer records create privacy and maintenance problems. The practical goal is synthetic data with believable structure, repeatable generation, and explicit control over edge cases.
Java Faker provides generators for people, addresses, companies, internet details, dates, numbers, and many other domains. It can produce values in different locales, which helps regional test suites avoid unrealistic combinations such as Australian cities attached to American phone formats. Its strongest use is supplying varied, valid-looking inputs to unit, integration, and API tests.
For Australian projects, realism includes more than substituting Sydney for New York. Local tests may need +61 mobile numbers, four-digit business postcodes, DD/MM/YYYY dates, Australian English, and prices in AUD with 10% GST. Java Faker handles much of this foundation, while a small domain factory adds the business rules that the library cannot infer.
Set up Java Faker for Australian tests
The maintained Java Faker project is published under the net.datafaker coordinates. Add it with test scope and pin the version used by your build:
<dependency>
<groupId>net.datafaker</groupId>
<artifactId>datafaker</artifactId>
<version>${datafaker.version}</version>
<scope>test</scope>
</dependency>
A locale-aware instance provides Australian names and address-related values while retaining access to the full API:
import net.datafaker.Faker;
import java.util.Locale;
Faker faker = new Faker(Locale.forLanguageTag("en-AU"));
String name = faker.name().fullName();
String email = faker.internet().emailAddress();
String city = faker.address().city();
String postcode = faker.address().postcode();
Locale support changes the shape of generated data, but it does not guarantee compliance with a particular application. An address might still use a postcode outside your accepted range, and an email address might not match a local deliverability policy. Keep domain assertions close to the tests that depend on them.
For reproducible failures, create the Faker instance with a controlled random seed. This makes a failing sequence repeatable without publishing the original customer data:
Faker faker = new Faker(
Locale.forLanguageTag("en-AU"),
new Random(20250308L)
);
Use a distinct seed for tests that need independent values. Parallel workers should not share mutable builders or identical fixtures, particularly when the application enforces email, customer, or account uniqueness.
Create Australian data that fits your domain
A reusable factory is usually more valuable than calling Faker directly throughout a test suite. It gives the project one place to define naming, address, phone, and currency conventions. Start with the smallest domain object your tests need rather than reproducing every field from a production schema.
public record CustomerPayload(
String fullName,
String email,
String mobile,
String city,
String postcode
) {
}
The corresponding factory can combine standard generators with a few explicit Australian rules:
public final class AustralianCustomerFactory {
private static final Faker FAKER =
new Faker(Locale.forLanguageTag("en-AU"));
private AustralianCustomerFactory() {
}
public static CustomerPayload customer() {
String mobile = String.format(
"+61 4%08d",
FAKER.random().nextInt(100_000_000)
);
return new CustomerPayload(
FAKER.name().fullName(),
FAKER.internet().emailAddress(),
mobile,
FAKER.address().city(),
FAKER.address().postcode()
);
}
}
This approach supports cities such as Sydney, Melbourne, Brisbane, and Perth while keeping phone numbers compatible with the Australian +61 country code and 04 mobile prefix. Domain-specific formatting remains visible, so a future change to accepted regions or number ranges requires one edit.
Local dates and timestamps deserve similar attention. Australian business systems commonly display dates as DD/MM/YYYY, and daylight-saving rules differ between states: Brisbane does not observe daylight saving, while Sydney and Melbourne do. Generate instants in the relevant ZoneId and assert the formatted result rather than assuming every Australian location uses the same offset.
Identifiers and validated fields need extra care. A random string that resembles an ABN, Australian account number, or tax reference may still fail a checksum. Build such values through a dedicated provider or apply the same validation used by the service. For Spring APIs, custom Spring validators can verify generated fields against production-style constraints.
Match generation strategies to test goals
Choose the generation method according to the behaviour being tested. Faker is effective for broad variation, but it is not a replacement for deliberate boundary and invalid-value fixtures.
| Data need | Hand-written constants | Java Faker output | Domain-specific factory |
|---|---|---|---|
| Personal identity | Repeated generic names | Varied localised names | Unique records linked across services |
| Address | One fixed street and city | Australian-style cities and postcodes | Accepted suburbs, postcodes, and regions |
| Financial value | Round numbers such as 100 |
Varied random amounts | AUD subtotal with consistent GST |
| Invalid input | Mutating a valid fixture | Usually produces valid-looking data | One explicit constraint violation at a time |
Faker provides the variety, while the factory provides consistency. A random price of 83.472 may be realistic for a general dataset but awkward for an Australian retail test that expects currency at two decimal places and GST calculated on a defined subtotal. A factory can return a precise BigDecimal, apply the 10% GST rule, and expose both values for assertions.
Negative testing should deliberately bypass normal generation. Produce a three-digit postcode, an expired date, or a malformed email when that is the specific condition under examination. Avoid combining several defects in one fixture because the resulting response may reveal only the first validation failure and hide regressions in later checks.
Treat generated realism as a range, not a guarantee of semantic truth. Localised names can still be duplicated, free-text fields can contain accidental profanity, and syntactically valid email addresses can resemble disposable addresses. Add repository-level checks or post-processing only where the application has a documented requirement.
Generate payloads for APIs and asynchronous workflows
API tests benefit from factories that produce complete request bodies without scattering JSON construction across test classes. Serialising a typed payload with Jackson or another JSON mapper ensures that field names and types match the contract:
CustomerPayload customer = AustralianCustomerFactory.customer();
String requestBody = objectMapper.writeValueAsString(customer);
mockServer.stubFor(request()
.withPath("/customers")
.withHeader("Content-Type", matching("application/json"))
.withBody(requestBody)
.willReturn(aResponse().withStatus(201)));
Keep infrastructure identifiers separate from business attributes. A customer ID may be better represented by a UUID, while Faker supplies the name, email, location, and contact details. Correlation IDs, idempotency keys, and event IDs should remain unique across the test run so asynchronous assertions can connect the request, queued message, and eventual response.
For backend jobs and event-driven systems, generate data for every state transition. A useful event fixture might contain a synthetic customer, an order value, a job identifier, and timestamps for creation and processing. The timestamps should be deterministic or controlled relative to the current clock; otherwise a test scheduled near midnight or during a daylight-saving transition can fail intermittently.
Assertions must follow the asynchronous contract. Use bounded polling or Awaitility to wait for the expected status, then check the consumed event rather than sleeping for an arbitrary period. Retries should use the same idempotency key, and duplicate events should be distinguishable from duplicate customers. This separation prevents a realistic payload from masking the ordering or deduplication behaviour the test is intended to examine.
Keep generated data reliable in the suite
Data quality checks should reflect the rules that the application actually enforces.
Useful fixture checks
- Confirm required formats, including postcode length and phone prefix.
- Keep field combinations consistent, such as currency, country, and tax rules.
- Verify uniqueness within a test run where the database requires it.
- Assert boundary values separately from normal generated records.
Automation safeguards
- Use a fixed seed to reproduce a failure.
- Keep generated records synthetic and free of real customer information.
- Centralise locale-specific transformations in a factory.
- Limit the data dependency to test code and fixtures.
Failure messages should identify the property that failed without printing an entire generated object. An assertion such as postcode must match \\d{4} is more actionable than a generic mismatch containing every field. Include the seed in the test report when reproducibility matters, because rerunning with a new random sequence can hide an intermittent defect.
The next concrete step is to add one AustralianCustomerFactory to the current API test module and replace its first hard-coded customer with a Faker-generated record in CI.