Skip to content

Domains

A property checks a rule for every value it draws, so it’s only as good as what it draws. Draw numbers that are too small and the bug at the edge never shows. Draw values that can’t happen and the property fails for no reason. A domain says which values can be drawn. This page starts with numbers, then builds up to records, then to a value that can be one of several kinds.

The examples are about trades. Each property is a method in a JUnit test class, with two static imports: io.proptastic.Proptastic.* and io.proptastic.bounds.Bounds.*.

integers() draws any int. Bound it to the values that make sense:

DomainsTest.java
static Domain<Integer> quantities() {
return integers().atLeast(1).atMost(10_000);
}
static Domain<Integer> pricesInCents() {
return integers().greaterThan(0).lessThan(1_000_000);
}
Bound Means So
.atLeast(1) 1 or more a quantity of 1 can be drawn
.atMost(10_000) 10,000 or less so can 10,000
.greaterThan(0) more than 0 a price of 0 can’t be drawn
.lessThan(1_000_000) less than 1,000,000 nor can 1,000,000

longs() and doubles() take the same four bounds. booleans() draws true or false.

A domain goes into forAll(…), and the lambda names what it draws:

DomainsTest.java
@Test
void aQuantitySplitsIntoTwoLots() {
forAll(quantities())
.check(
quantity -> {
int firstLot = quantity / 2;
int secondLot = quantity - firstLot;
assertEquals(quantity, firstLot + secondLot);
});
}

proptastic doesn’t draw evenly. It leans to small values and to the far end of a range, because bugs live at the edges: here 1 and 10,000 come up far more often than an even draw would give them. How values are drawn says how often, for every domain.

elements(…) draws one of the values you give it. any(…) draws any value of an enum:

DomainsTest.java
static Domain<String> symbols() {
return elements("AAPL", "MSFT", "NVDA");
}
static Domain<Side> sides() {
return any(Side.class);
}

The first value is the simplest. When a property fails, proptastic shrinks toward "AAPL" and BUY.

strings() draws text of any length up to 100 characters. .ofLength(…) takes the same bound words as a size:

DomainsTest.java
static Domain<String> notes() {
return strings().ofLength(atMost(20));
}

Some text has rules of its own: a ticker is a few capital letters, an order id letters and digits. .from(…) draws only the characters it’s given, and takes the alphabets proptastic names, or a string of your own, .from("ACGT"):

DomainsTest.java
static Domain<String> tickers() {
return strings().from(UPPERCASE).ofLength(atLeast(1), atMost(5));
}
static Domain<String> orderIds() {
return strings().from(UPPERCASE, DIGITS).ofLength(12);
}

The named alphabets are DIGITS, HEX_DIGITS, LOWERCASE, UPPERCASE, LETTERS, ALPHANUMERIC, PRINTABLE_ASCII and WHITESPACE, all ASCII. The first character given is the simplest, the one a failure shrinks to.

Two words keep the awkward characters but leave out what the code can’t take. .nonBlank() draws text with at least one character that isn’t whitespace, so a name or a comment that has to say something does. .singleLine() leaves out line breaks, for a field that ends at the end of the line:

DomainsTest.java
static Domain<String> accountNames() {
return strings().nonBlank().singleLine().ofLength(atMost(40));
}
DomainsTest.java
@Test
void anAccountNameStripsToSomething() {
forAll(accountNames()).check(name -> assertThat(name.strip()).isNotEmpty());
}

Neither throws a value away: a string drawn all spaces and tabs gets one of its characters drawn again from the rest, and a line break is never drawn at all. A filter, .filter(name -> !name.isBlank()), would throw away a good share of what strings() draws, as it draws spaces and tabs often, and a failure would shrink less well.

lists(…), sets(…) and maps(…) draw Java’s own collections, of values from the domains you give them. .ofSize(…) bounds how many:

DomainsTest.java
static Domain<List<String>> baskets() {
return lists(symbols()).ofSize(atLeast(1), atMost(5));
}
static Domain<Set<String>> watchlists() {
return sets(symbols());
}
static Domain<Map<String, Integer>> holdings() {
return maps(symbols(), quantities());
}

.ofSize(3) is exactly three, and .nonEmpty() is at least one. Without a size, a collection holds 0 to 100 values, and usually only a few. optionals(…) draws an Optional, sometimes empty.

.map(…) turns each value into another. Shares often trade in round lots of 100:

DomainsTest.java
static Domain<Integer> roundLots() {
return integers().atLeast(1).atMost(100).map(lots -> lots * 100);
}
static Domain<Integer> roundLotsByFilter() {
return quantities().filter(quantity -> quantity % 100 == 0);
}
DomainsTest.java
@Test
void aRoundLotIsAWholeNumberOfHundreds() {
forAll(roundLots()).check(quantity -> assertEquals(0, quantity % 100));
}

.filter(…) keeps only the values that pass, and draws again for the rest. Both domains above draw round lots, but the filter throws most of its draws away to do it, and after 100 rejections in a row it gives up on that try. The two don’t draw the same mix either: map, filter and flatMap shows how. Prefer .map(…), and keep .filter(…) for rules that rarely say no.

A run checks this for you. Over its first 100 tries, if filters reject more than 3 in 4 of the values they draw, it fails a health check before spending its tries:

HealthTest.java
@Test
void aRoundLotIsAWholeNumberOfHundreds() {
forAll(roundLotsByFilter()).check(lot -> assertEquals(0, lot % 100));
}
aRoundLotIsAWholeNumberOfHundreds failed a health check (seed 0x5eed)
filter:
filters rejected 1,628 of the 1,728 values they drew in the first 100 tries, over 3 in 4
rerun:
PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'HealthTest.aRoundLotIsAWholeNumberOfHundreds'
! build values that meet the filter, in place of discarding the rest
! or say why it's fine: .allow("filter", "…")

So does a run that discards more than 3 in 4 tries with assume(…), and one where more than 1 in 4 draws take over 10,000 choices (large): a domain drawing more than the check needs. Drawing that takes over a second only warns (slow), as a busy machine draws slowly too. Where a check is fine for a property, say why, and it isn’t made:

HealthTest.java
@Test
void aRoundLotByFilterIsAWholeNumberOfHundreds() {
forAll(roundLotsByFilter())
.allow("filter", "this page shows the filter's cost")
.check(lot -> assertEquals(0, lot % 100));
}

.excluding(…) leaves out the values you name. A divisor can be anything but zero:

DomainsTest.java
static Domain<Integer> divisors() {
return integers().atLeast(-1_000).atMost(1_000).excluding(0);
}
@Test
void dividingThenMultiplyingGivesTheNumberBack() {
forAll(integers(), divisors())
.check(
(number, divisor) -> {
var back = number / divisor * divisor + number % divisor;
assertEquals(number, back);
});
}

A whole number, one of elements(…) or a date steps over the values by its index, so none is ever drawn, nothing is thrown away, and a counterexample shrinks past them to the next simplest value, here 1. On any other domain .excluding(…) is a filter that names its values, and the health check counts what it rejects. A value the domain can’t draw is no matter. Say the bounds first: like .edges(…), it ends a chain.

Some checks only make sense when the drawn values fit together. Clamping a value into a range only means something when the range’s low end isn’t above its high end, and that’s a rule about two values at once, which no one domain can say. assume(…) says it inside the check: when its condition doesn’t hold, the try is skipped, neither passed nor failed, and the run draws another in its place.

AssumeTest.java
@Test
void clampingKeepsAValueInItsRange() {
forAll(integers(), integers(), integers())
.check(
(value, low, high) -> {
assume(low <= high);
int clamped = clamp(value, low, high);
assertTrue(low <= clamped && clamped <= high);
});
}

Reach for it last. For a rule about one value, build a domain that only draws what you want: integers().atLeast(1) rather than assume(n > 0), as it never wastes a try and shrinks within the rule. For a rule about one value that’s hard to build, .filter(…) on that domain keeps the rule beside the values it’s about. assume(…) is for what’s left: a condition across several drawn values, or one the check only learns partway through.

A skipped try is a try that checked nothing. Here the run passes, so few enough were skipped. Ask for something rarer, and most tries are thrown away; once more than 3 in 4 of the first 100 are, the run fails the filter health check instead of passing on the few that got through:

AssumeTest.java
@Test
void clampingIntoOneValueGivesThatValue() {
forAll(integers(), integers(), integers())
.check(
(value, low, high) -> {
assume(low.equals(high));
assertEquals(low, clamp(value, low, high));
});
}
clampingIntoOneValueGivesThatValue failed a health check (seed 0x5eed)
filter: 100 of the first 100 tries were discarded, over 3 in 4
rerun: PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'AssumeTest.clampingIntoOneValueGivesThatValue'
! build values that meet the filter, in place of discarding the rest
! or say why it's fine: .allow("filter", "…")

Draw what the check needs instead: here, one bound, passed as both ends.

JUnit’s own assumeTrue(…) works the same inside a check: proptastic skips the try, rather than skipping the whole test as JUnit would, so a property written with JUnit’s assumptions runs as you’d expect:

AssumeTest.java
@Test
void clampingKeepsAValueInItsRangeWithJUnit() {
forAll(integers(), integers(), integers())
.check(
(value, low, high) -> {
assumeTrue(low <= high);
int clamped = clamp(value, low, high);
assertTrue(low <= clamped && clamped <= high);
});
}

A trade is a record:

Trade.java
record Trade(String symbol, Side side, int quantity, int priceInCents) {
int valueInCents() {
return quantity * priceInCents;
}
}

domain(…) builds a record from the domains you already have. It draws a value from each, and passes them, in order, to the constructor:

DomainsTest.java
static Domain<Trade> trades() {
return domain(symbols(), sides(), quantities(), pricesInCents(), Trade::new);
}

A trade’s value is its quantity times its price. Check that:

DomainsTest.java
@Test
void aTradesValueIsItsQuantityTimesItsPrice() {
forAll(trades())
.check(
trade -> {
long expected = (long) trade.quantity() * trade.priceInCents();
assertEquals(expected, trade.valueInCents());
});
}

It fails:

Terminal window
expected: <2147485880> but was: <-2147481416>
aTradesValueIsItsQuantityTimesItsPrice failed after 28 tries (seed 0xb6fa8422087bd6db)
shrunk counterexample: trade = new Trade("AAPL", Side.BUY, 6520, 329369) // Trade(symbol, side, quantity, priceInCents)
pin it: .example(new Trade("AAPL", Side.BUY, 6520, 329369))
rerun: PROPTASTIC_SEED=0xb6fa8422087bd6db ./gradlew test --tests 'DomainsTest.aTradesValueIsItsQuantityTimesItsPrice'

valueInCents() multiplies two ints, and the answer is just past the largest int, 2,147,483,647. So it wraps around to a negative number. The counterexample shows why the bounds matter: with prices bounded by a few dollars, the product would never get that big, and the property would pass. A record prints as the constructor call that makes it, so the pin it: line pastes straight into your test.

A trade like this isn’t round, as a small list or a zero would be. proptastic made each number as small as it could while the product still overflowed. Make one smaller and the bug is gone.

When a record has many fields, it can be easier to read with each one named where it’s drawn. domain(source -> …) hands you a source to draw from:

DomainsTest.java
static Domain<Trade> tradesByName() {
return domain(
source ->
new Trade(
source.draw(symbols()),
source.draw(sides()),
source.draw(quantities()),
source.draw(pricesInCents())));
}

Values are drawn in the order written. Use the first form when a constructor takes the values in order, and this one when you need to work something out between two draws.

An order is either a market order or a limit order:

Order.java
/** An order to buy: at whatever the market asks, or at a limit or less. */
sealed interface Order permits MarketOrder, LimitOrder {
String symbol();
String describe();
}
MarketOrder.java
record MarketOrder(String symbol, int quantity) implements Order {
@Override
public String describe() {
return "buy %d %s at market".formatted(quantity, symbol);
}
}
LimitOrder.java
record LimitOrder(
String symbol, // what to buy
int quantity, // how many shares
int limitInCents) // the most it pays a share
implements Order {
@Override
public String describe() {
var shares = quantity + " " + symbol;
return "buy " + shares + " at " + limitInCents + " cents or less";
}
}

Build a domain for each kind, then oneOf(…) picks one of them and draws from it:

DomainsTest.java
static Domain<Order> orders() {
return oneOf(marketOrders(), limitOrders());
}
static Domain<MarketOrder> marketOrders() {
return domain(symbols(), quantities(), MarketOrder::new);
}
static Domain<LimitOrder> limitOrders() {
return domain(symbols(), quantities(), pricesInCents(), LimitOrder::new);
}
DomainsTest.java
@Test
void anOrderNamesItsSymbol() {
forAll(orders())
.check(
order -> {
var description = order.describe();
assertThat(description).contains(order.symbol());
});
}

Like elements(…), oneOf(…) counts its first choice as the simplest. Put the plainest kind first, and a counterexample shrinks toward it.

any(…) does the same from the type. A sealed interface or class is a oneOf(…) of the subtypes it permits, in the order it permits them, and each record is drawn component by component. From Kotlin, a data class is drawn the same way, through its primary constructor, an object is its one instance, and a sealed class or sealed interface is its subtypes:

DomainsTest.java
@Test
void anyOrderNamesItsSymbol() {
forAll(any(Order.class))
.check(
order -> {
var description = order.describe();
assertThat(description).contains(order.symbol());
});
}

It draws each component as any(…) of its type would: any String, any int, negative ones and all. Where the values matter, give a component its own domain with .with(…), naming it by its accessor:

DomainsTest.java
static Domain<Trade> anyTrades() {
return any(Trade.class)
.with(Trade::symbol, symbols())
.with(Trade::quantity, quantities())
.with(Trade::priceInCents, pricesInCents());
}

This draws what trades() draws, the side from its enum. .with(…) reaches its record wherever it’s drawn, however deep: any(Order.class).with(Line::quantity, quantities()) bounds every line of every order. Naming a component the type never holds is refused, so a typo can’t pass unnoticed.

In Kotlin, any(…) draws a data class through its primary constructor, and .with(…) names a property, from the proptastic-kotlin jar (Install):

WithTest.kt
fun orders(): Domain<Order> =
any(Order::class.java)
.with(Order::customer, elements("ada", "grace"))
.with(Line::quantity, longs().atLeast(1).atMost(9))

It’s an extension, import io.proptastic.with, taking Kotlin’s own property reference, so a renamed property breaks at compile time there too. A property outside the primary constructor, or of a class that isn’t a data class, is refused.

A type can hold itself: record Add(Expr left, Expr right) implements Expr, or a Tree with a List<Tree> of children. any(…) draws them too, and every draw ends: a few levels down, a sealed type draws only the subtypes that don’t hold it again, and a list of it draws a quarter as many at each level. A record that holds itself with no way to stop, record Loop(Loop next), is refused with what to change.

Plenty of codebases still keep dates in Joda-Time, which its own site calls a largely finished project, asking users to move to java.time (Joda-Time). Amounts with a currency often live in Joda-Money. proptastic has no words for either, and needs none. Draw proptastic’s own value and map it to theirs, and everything the domain knows comes with it.

dates() with .excluding(…) draws business days by construction, and map turns each into Joda’s LocalDate:

JodaTest.java
static Domain<org.joda.time.LocalDate> jodaWeekdays() {
return dates()
.atLeast(java.time.LocalDate.of(2026, 1, 1))
.atMost(java.time.LocalDate.of(2026, 12, 31))
.excluding(SATURDAY, SUNDAY)
.map(
day ->
new org.joda.time.LocalDate(
day.getYear(), day.getMonthValue(), day.getDayOfMonth()))
.writtenAs(day -> "org.joda.time.LocalDate.parse(\"" + day + "\")");
}

writtenAs says how to write a value as Java source, which proptastic can’t do for a type it doesn’t know. With it, a failure’s pin line is the value itself, ready to paste into .example(…); without it, the pin is the seed, which stops drawing the same value the moment the domain changes.

Here’s a desk’s settlement code, still on Joda, and the property it should keep:

Settlement.java
/** The next business day: a day on, and past a Saturday. */
static LocalDate settle(LocalDate trade) {
var next = trade.plusDays(1);
if (next.getDayOfWeek() == DateTimeConstants.SATURDAY) {
next = next.plusDays(1);
}
return next;
}
JodaTest.java
@Test
void aTradeSettlesOnAWeekday() {
forAll(jodaWeekdays())
.check(
trade ->
assertThat(Settlement.settle(trade).getDayOfWeek())
.isLessThanOrEqualTo(DateTimeConstants.FRIDAY));
}
Terminal window
Expecting actual:
7
to be less than or equal to:
5
aTradeSettlesOnAWeekday failed after 2 tries (seed 0x5eed)
shrunk counterexample: trade = 2026-01-02
pin it: .example(org.joda.time.LocalDate.parse("2026-01-02"))
rerun: PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'JodaTest.aTradeSettlesOnAWeekday'

A Friday’s settlement lands on a Sunday. It shrank to Friday 2 January 2026, the first in the range, because it was drawn as a java.time date: the weekdays-only construction, the calendar edges and the shrinking toward the start of the range all carried over, and the pin line writes the day as writtenAs said. Drawing Joda’s milliseconds since 1970 as a long instead would lose all of that: no weekends left out, no month ends or leap days aimed at, and a failure shrinking to 1 January 1970, the date most code reads as “unset”. Dates says what the date domains draw.

An amount is a currency and a number of its minor units, so drawing the minor units makes every amount valid for its currency, whatever its decimal places: none for the yen, two for the dollar and the pound, three for the Bahraini and Kuwaiti dinars.

JodaTest.java
static final CurrencyUnit[] CURRENCIES = {
CurrencyUnit.USD,
CurrencyUnit.JPY,
CurrencyUnit.GBP,
CurrencyUnit.of("BHD"),
CurrencyUnit.of("KWD")
};
/** An amount drawn as minor units: always valid for its currency. */
static Domain<Money> money() {
var minorUnits = longs().atLeast(-1_000_000_000).atMost(1_000_000_000);
return domain(elements(CURRENCIES), minorUnits, Money::ofMinor)
.writtenAs(amount -> "Money.parse(\"" + amount + "\")");
}

domain(…) draws the currency, then the minor units, then makes the Money. A counterexample shrinks toward zero in the first currency, USD 0.00, and pins as Money.parse("USD 0.00"). The properties money code should keep: adding then taking away gives the amount back, a split sums back to the whole, and a rounding with a RoundingMode keeps the currency’s places and lands within half a minor unit:

JodaTest.java
@Test
void addingThenTakingAwayGivesTheAmountBack() {
forAll(money(), longs().atLeast(-1_000_000).atMost(1_000_000))
.check(
(amount, minor) -> {
var other = Money.ofMinor(amount.getCurrencyUnit(), minor);
assertEquals(amount, amount.plus(other).minus(other));
});
}
@Test
void aSplitSumsBackToTheWhole() {
forAll(money(), integers().atLeast(1).atMost(12))
.check(
(amount, parts) -> {
var share = amount.dividedBy(parts, RoundingMode.DOWN);
var others = share.multipliedBy(parts - 1);
var last = amount.minus(others);
assertEquals(amount, others.plus(last));
var over = last.minus(share).abs();
assertThat(over.getAmountMinorLong()).isLessThan(parts);
});
}
@Test
void roundingAFeeKeepsTheCurrencysPlaces() {
var rates = decimals().atLeast(BigDecimal.ZERO).atMost(BigDecimal.ONE);
forAll(money(), rates.places(4))
.check(
(amount, rate) -> {
var fee = amount.multipliedBy(rate, RoundingMode.HALF_EVEN);
var places = amount.getCurrencyUnit().getDecimalPlaces();
assertEquals(places, fee.getAmount().scale());
var exact = amount.getAmount().multiply(rate);
var off = fee.getAmount().subtract(exact).abs();
var halfAMinorUnit = new BigDecimal("0.5").movePointLeft(places);
assertThat(off).isLessThanOrEqualTo(halfAMinorUnit);
});
}

A fee of one percent, rounded half-even, is zero whenever one percent of the amount is at most half a minor unit, as exactly half rounds to the even neighbour, 0: any amount up to and including 50 cents. An amount of zero has a zero fee too, but that’s no surprise, so the filter leaves it out:

JodaTest.java
@Test
void aFeeIsNeverZero() {
var onePercent = new BigDecimal("0.01");
forAll(money().filter(amount -> !amount.isZero()))
.check(
amount -> {
var fee = amount.multipliedBy(onePercent, RoundingMode.HALF_EVEN);
assertThat(fee.isZero()).isFalse();
});
}
Terminal window
Expecting value to be false but was true
aFeeIsNeverZero failed after 4 tries (seed 0x5eed)
shrunk counterexample: amount = USD 0.01
pin it: .example(Money.parse("USD 0.01"))
rerun: PROPTASTIC_SEED=0x5eed ./gradlew test --tests 'JodaTest.aFeeIsNeverZero'

This is the recipe for money with a currency. proptastic doesn’t ship a list of currencies: like holidays, ISO 4217 changes, and the list your code accepts is yours.

How values are drawn says how often each domain draws what, and how to change it. A bank account puts these together: a list of operations, each one of three kinds, checked after every step. The patterns are the kinds of rule worth checking on what you draw.

Privacy