Randomized test data generates varied inputs at runtime instead of fixing every value in advance. It helps tests explore more reachable program states and expose hidden coupling. section 11.0 section 11.5
Use randomization to make tests broader without obscuring the values that actually matter:
- Randomize unused attributes so tests cannot depend on another method’s hidden, hard-coded values. section 11.4.1
- Specialize only relevant attributes explicitly, using overloaded generators or data-type withers. section 11.4.1
- Interpret randomized fields as assertions that the tested behavior should hold across all generated values, not as values that do not matter. section 11.4.1
- Keep deterministic examples when the interesting state space is already completely and clearly enumerated. section 11.5.6
Customizing a randomized account
A base generator can randomize an Account’s identifier, region, currency amount, segment, sector, and timestamp. A test then specializes only what matters: mkAcnt().withSegment(ENTERPRISE), or mkAcnt().withRegion(region).withSpend(threshold.plus(1)). section 11.4.1
Listing 11.34 Generating randomized test data
Random rand = new Random();
Account mkAcnt() {
List<String> sectors = List.of(
"Finance",
"healthcare",
"..."
);
return new Account(
new AccountId(format("%09d", rand.nextLong(999999999))), #A
Region.values()[rand.nextInt(Region.values().length)], #A
new USD(BigDecimal.valueOf(rand.nextDouble(USD_ZERO, USD_MAX))), #A
Segment.values()[rand.nextInt(Segment.values().length)], #A
new Sector(sectors.get(rand.nextInt(sectors.size()))), #A
Instant.ofEpochSecond(rand.nextLong(99999999999L)) #A
);
}
static double USD_ZERO = 0.0; #B
static double USD_MAX = pow(10, 15); #BInspect the Java generator that creates randomized account identifiers, regions, amounts, segments, sectors, and timestamps. section 11.4.1
