How to Do Property Based Testing With jqwik in Java
Write property based tests with jqwik: generators, shrinking, custom arbitraries for domain objects, round trip properties and seeds.

Example based tests check what the author thought of. A test for a parsing function tries a normal string, an empty string and perhaps a null, then stops, and the bug lives in the input nobody imagined: a string with a trailing newline, a surrogate pair, a negative zero. Property based testing turns the question around. Instead of writing examples, you state a rule that must hold for every valid input, and the framework generates hundreds of inputs, including awkward ones, hunting for a counterexample. If it finds one, it shrinks it to the smallest failing input, which is usually all you need to see the bug. jqwik is the property based testing engine for the JUnit Platform, so properties run beside your ordinary tests. This post builds up from a first property to custom generators for domain objects and covers the patterns for finding properties, how failures are reported and reproduced and where the approach does not help. The example based tests it complements are in the Java testing strategy, and the readable assertions used below are covered in AssertJ fluent assertions and JUnit 5 parameterized tests.
Setup
jqwik runs as a JUnit Platform engine, so the dependency is a test scope and the existing build runs it:
<dependency>
<groupId>net.jqwik</groupId>
<artifactId>jqwik</artifactId>
<version>1.9.2</version>
<scope>test</scope>
</dependency>If JUnit Jupiter tests and jqwik properties coexist, both engines run under the same Maven Surefire or Gradle test task. Check the compatibility note for the JUnit Platform version you use, since jqwik tracks the platform releases separately from Jupiter.
A first property
A property is a method annotated @Property whose parameters are marked @ForAll. jqwik chooses the values:
package dev.javahacks.props;
import net.jqwik.api.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class ListProperties {
@Property
void reversingTwiceGivesTheOriginalList(@ForAll List<Integer> original) {
List<Integer> copy = new ArrayList<>(original);
Collections.reverse(copy);
Collections.reverse(copy);
assertThat(copy).isEqualTo(original);
}
@Property
void sortedListsAreInAscendingOrder(@ForAll List<@IntRange(min = -1000, max = 1000) Integer> numbers) {
List<Integer> sorted = new ArrayList<>(numbers);
Collections.sort(sorted);
for (int i = 1; i < sorted.size(); i++) {
assertThat(sorted.get(i - 1)).isLessThanOrEqualTo(sorted.get(i));
}
}
}By default each property runs 1000 tries. For List<Integer>, jqwik generates lists of varying sizes, including the empty list, with integers across the whole range and with a bias towards edge cases such as zero, one, minus one and the extremes. The constraint annotations narrow the domain: @IntRange restricts the values, and there are others, @Size, @StringLength, @AlphaChars, @Positive, @NotBlank, @Unique. These properties pass because the rules hold; the interesting behaviour is when they do not.
Failure and shrinking
Write a property with a bug in the implementation, a hand written function to compute the average:
static int average(List<Integer> numbers) {
int sum = 0;
for (int n : numbers) {
sum += n;
}
return sum / numbers.size();
}
@Property
void theAverageIsBetweenTheMinimumAndTheMaximum(@ForAll @Size(min = 1) List<Integer> numbers) {
int avg = average(numbers);
assertThat(avg).isBetween(Collections.min(numbers), Collections.max(numbers));
}An example based test with [1, 2, 3] passes. The property fails:
Property [theAverageIsBetweenTheMinimumAndTheMaximum] failed with sample [2147483647, 1]
tries = 38
checks = 38
generation = RANDOMIZED
seed = 4123981298237
Shrunk Sample (13 steps)
------------------------
numbers: [2147483647, 1]
Original Sample
---------------
numbers: [-1034210001, 2112345988, 2051234001, 17, ...]
Original Error
--------------
java.lang.AssertionError: Expecting actual: -2147483648 to be between 1 and 2147483647Three things in that report earn their keep. The shrunk sample [2147483647, 1] is the minimal list that still fails: two numbers whose sum overflows int. jqwik arrived at it by repeatedly simplifying the original, a 50 element list, while the property kept failing. Without shrinking you would stare at a large random list; with it the cause is visible at a glance, the sum overflows. The seed is the number that makes the run reproducible. And the original error shows what actually happened. Fix the code to sum in a long and the property passes.
Reproduce a failure
To rerun the exact failing case, give jqwik the seed:
@Property(seed = "4123981298237")
void theAverageIsBetweenTheMinimumAndTheMaximum(@ForAll @Size(min = 1) List<Integer> numbers) { /* ... */ }By default jqwik also remembers failing properties in a .jqwik-database file and replays the previous failures first on the next run, so a fixed bug stays fixed and a flaky property cannot slip away. Commit the file only if the team wants shared regression seeds; keep it out of version control otherwise. When a property finds a real bug, add a plain @Example test for the shrunk case, so the specific regression is documented in the simplest form:
@Example
void averageDoesNotOverflow() {
assertThat(average(List.of(Integer.MAX_VALUE, 1))).isEqualTo(1_073_741_824);
}Properties find the bug; an example preserves it.
Finding properties
The hard part of property based testing is not the tool, it is thinking of properties. Five patterns cover most cases.
Round trip. Encoding then decoding returns the original. This catches an astonishing number of bugs in serialisers, parsers and codecs.
@Property
void jsonRoundTripPreservesAnOrder(@ForAll("orders") Order order) throws Exception {
String json = mapper.writeValueAsString(order);
assertThat(mapper.readValue(json, Order.class)).isEqualTo(order);
}Invariant. Something stays true across an operation: the size after add is one more, the sum of allocated shares equals the total, a balance never goes negative.
@Property
void allocatingMoneyNeverLosesACent(@ForAll @LongRange(min = 0, max = 10_000_000) long cents,
@ForAll @IntRange(min = 1, max = 20) int parts) {
List<Long> shares = Money.allocate(cents, parts);
assertThat(shares).hasSize(parts);
assertThat(shares.stream().mapToLong(Long::longValue).sum()).isEqualTo(cents);
assertThat(Collections.max(shares) - Collections.min(shares)).isLessThanOrEqualTo(1);
}This is the textbook case: splitting 100 cents into 3 parts. Any rounding bug that loses or invents a cent shows up for some (cents, parts) pair, and a handful of hand picked examples would not find it.
Compare with a simple model. Test a fast, complicated implementation against a slow, clearly right one.
@Property
void theFastSearchAgreesWithALinearScan(@ForAll List<@IntRange(min = 0, max = 50) Integer> values,
@ForAll @IntRange(min = 0, max = 50) int needle) {
List<Integer> sorted = values.stream().sorted().toList();
boolean expected = sorted.contains(needle);
boolean actual = Search.binary(sorted, needle) >= 0;
assertThat(actual).isEqualTo(expected);
}Idempotence. Doing it twice equals doing it once: normalising a string, canonicalising a path, formatting code.
Relationships. Output properties that follow from the input: the length of concat(a, b) is the sum of the lengths, a filter returns a subset, a sort returns a permutation, encode of different inputs gives different outputs.
A useful exercise on any function you write: finish the sentence "for all inputs, this function ..." and test the sentence.
Custom generators for domain objects
Random integers and lists are the easy cases. Domain objects need valid values: an email with an @, an order with at least one line, a date range where the end follows the start. jqwik builds them from arbitraries. Define a provider method for each type, annotated @Provide:
class OrderProperties {
@Provide
Arbitrary<String> emails() {
Arbitrary<String> local = Arbitraries.strings().alpha().ofMinLength(1).ofMaxLength(12);
Arbitrary<String> domain = Arbitraries.of("example.test", "mail.example.test", "shop.example.test");
return Combinators.combine(local, domain).as((l, d) -> l + "@" + d);
}
@Provide
Arbitrary<OrderLine> lines() {
Arbitrary<String> sku = Arbitraries.strings().withCharRange('A', 'Z').ofLength(2)
.map(s -> s + "-" + (int) (Math.random() * 100));
Arbitrary<Integer> quantity = Arbitraries.integers().between(1, 20);
Arbitrary<Long> price = Arbitraries.longs().between(1, 500_00);
return Combinators.combine(sku, quantity, price).as(OrderLine::new);
}
@Provide
Arbitrary<Order> orders() {
return Combinators.combine(emails(), lines().list().ofMinSize(1).ofMaxSize(8))
.as((email, lines) -> new Order(email, lines));
}
@Property
void theTotalIsTheSumOfTheLines(@ForAll("orders") Order order) {
long expected = order.lines().stream().mapToLong(l -> l.quantity() * l.unitPriceCents()).sum();
assertThat(order.totalCents()).isEqualTo(expected);
}
}@ForAll("orders") refers to the provider by name. Combinators.combine(...).as(...) is the key tool: it builds an object from independently generated parts, constrained at generation time, so every generated order is valid by construction. Prefer this to generating arbitrary data and discarding the invalid, with .filter(...) or Assume.that(...), which wastes tries and can fail with TooManyFilterMissesException when the filter rejects most inputs. A .filter on a rarely true predicate is a signal to build the value positively. Note that the Math.random() in the SKU provider above defeats reproducibility: a seed cannot replay it, because the randomness is outside jqwik's control. Use Arbitraries.integers() mapped into the string instead, so everything comes from the generator.
For records, jqwik can derive an arbitrary from the type with Arbitraries.defaultFor(...) and the @Domain / DomainContext mechanism, or from constructor and factory methods with Builders; for simple cases the explicit combine is clearer and has no surprises.
Controlling the run
The knobs on @Property shape the effort:
@Property(tries = 5000, maxDiscardRatio = 10, shrinking = ShrinkingMode.FULL, edgeCases = EdgeCasesMode.MIXIN)
void aThoroughProperty(@ForAll int x) { /* ... */ }tries raises or lowers the number of inputs; a deep property in a nightly build can use many thousands, while the default is right for a pull request. edgeCases decides how often the engine tries the extremes (zero, empty, maximum) as part of the stream. shrinking = BOUNDED limits the shrinking effort for expensive properties. Statistics.collect(...) is a diagnostic: record what your generators actually produce and check the distribution, because a generator that mostly emits trivial cases tests little:
@Property
void ordersHaveAReasonableMix(@ForAll("orders") Order order) {
Statistics.collect(order.lines().size() > 4 ? "many lines" : "few lines");
}[OrderProperties:ordersHaveAReasonableMix] (1000) statistics:
few lines (621) : 62 %
many lines (379) : 38 %If one category is under represented, adjust the generator. The cost in test time is also yours to budget: a property making a database call a thousand times is a slow test. Properties belong at the unit level, on pure logic where each try takes microseconds.
Stateful and sequence testing
Beyond functions, jqwik can test stateful systems by generating sequences of actions and checking an invariant after each, via its Action and ActionSequence support. A shopping basket that supports add, remove and clear can be checked with random sequences against a model, a plain Map, to find the sequence of operations that breaks it. It finds bugs of the "this works alone but fails after remove then add" variety, which example tests rarely cover. The setup is more involved than function level properties, so reserve it for components with non trivial state: caches, state machines, in memory stores.
Pitfalls
Properties that restate the implementation. A test that computes the expected value with the same algorithm proves nothing. Use a different method (a model, an inverse, a relationship).
Weak properties. "The result is not null" passes for wrong results. Pair each property with the strongest statement you can make.
Hidden non determinism. Anything outside jqwik's generators, Random, the current time, hash ordering from a HashSet iteration used for assertions, breaks reproducibility. Inject clocks and seed generators.
Unbounded generators. @ForAll String includes huge strings and unusual Unicode; if the code under test has limits, constrain the domain or the property fails for a reason you do not care about.
Treating it as a replacement. Properties complement example tests, which document specific scenarios and regressions in readable form.
When this does not apply
Code that is mostly I/O and wiring, such as controllers, repositories and configuration, has few useful properties and is better checked with examples and integration tests. Rules with arbitrary business tables, a tax rate per country, are best written as parameterised example tests. If your team has never used the technique, begin with one round trip property on a codec or parser; it often finds a bug on the first run. The references are the jqwik user guide and John Hughes's introduction to QuickCheck style testing, the idea's origin.


