jqwik Property-Based Testing in Java: Properties, Arbitraries, and Shrinking

jqwik Property-Based Testing in Java: Properties, Arbitraries, and Shrinking

Java developers using JUnit 5 have two mature property-based testing options: QuickTheories and jqwik. jqwik is the more actively maintained and integrates directly with JUnit 5 as a test engine, meaning it runs alongside regular @Test methods without any special configuration.

Property-based testing generates hundreds or thousands of random inputs and checks that your invariants hold for all of them. When a failure is found, jqwik automatically shrinks the input to the minimal failing case — so instead of debugging a failure with a 47-element list, you get the simplest 2-element list that reproduces it.

Setup

Add jqwik to your Maven or Gradle project. It replaces JUnit 5's default test engine for @Property methods while leaving @Test methods intact:

<!-- Maven -->
<dependency>
    <groupId>net.jqwik</groupId>
    <artifactId>jqwik</artifactId>
    <version>1.8.4</version>
    <scope>test</scope>
</dependency>
// Gradle
testImplementation 'net.jqwik:jqwik:1.8.4'

No additional configuration needed. jqwik registers as a JUnit Platform test engine via the service loader mechanism.

Your First Property

A @Property method runs 1000 times by default (configurable), each time with generated input:

import net.jqwik.api.*;

class StringReverseProperties {

    @Property
    void reversingTwiceGivesOriginal(@ForAll String anyString) {
        String reversed = reverse(reverse(anyString));
        Assertions.assertThat(reversed).isEqualTo(anyString);
    }

    @Property
    void reversingPreservesLength(@ForAll String anyString) {
        Assertions.assertThat(reverse(anyString).length())
            .isEqualTo(anyString.length());
    }

    private String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }
}

@ForAll tells jqwik to generate values for that parameter. For standard types (String, Integer, List, etc.), jqwik has built-in generators. For custom types, you define Arbitrary instances.

Built-in Generators

jqwik generates sensible values for most Java types:

@Property
void integerArithmetic(@ForAll int x, @ForAll int y) {
    // Commutative property
    Assumptions.assumeThat(x + y).isEqualTo(y + x);
}

@Property
void listNotNullWhenGenerated(@ForAll List<String> strings) {
    Assertions.assertThat(strings).isNotNull();
}

@Property
void optionalIsEitherEmptyOrPresent(@ForAll Optional<String> opt) {
    Assertions.assertThat(opt.isEmpty() || opt.isPresent()).isTrue();
}

Constraining Generators

Use annotations to restrict the range of generated values:

@Property
void positiveNumberSquaredIsPositive(
        @ForAll @Positive int n) {
    Assertions.assertThat(n * n).isPositive();
}

@Property
void emailLength(
        @ForAll @NotBlank @StringLength(min = 1, max = 255) String email) {
    // String has length between 1 and 255
    Assertions.assertThat(email.length()).isBetween(1, 255);
}

@Property
void numbersInRange(
        @ForAll @IntRange(min = 1, max = 100) int percentile) {
    Assertions.assertThat(percentile).isBetween(1, 100);
}

Available constraint annotations: @Positive, @Negative, @IntRange, @LongRange, @FloatRange, @DoubleRange, @BigRange, @StringLength, @NotBlank, @Size, @NotEmpty, @UniqueElements, @WithNull.

Custom Arbitraries

For domain types, define an Arbitrary using jqwik's fluent API:

class OrderProperties {

    @Provide
    Arbitrary<Order> validOrders() {
        Arbitrary<String> customerId = Arbitraries.strings()
            .withCharRange('a', 'z')
            .ofMinLength(5)
            .ofMaxLength(20)
            .map(id -> "cust_" + id);

        Arbitrary<Money> amount = Arbitraries.bigDecimals()
            .between(BigDecimal.ONE, new BigDecimal("10000"))
            .ofScale(2)
            .map(d -> Money.of(d, "USD"));

        Arbitrary<List<OrderItem>> items = validOrderItems().list()
            .ofMinSize(1)
            .ofMaxSize(10);

        return Combinators.combine(customerId, amount, items)
            .as((id, amt, itemList) -> new Order(id, amt, itemList));
    }

    @Provide
    Arbitrary<OrderItem> validOrderItems() {
        return Combinators.combine(
            Arbitraries.strings().withChars("PROD").ofLength(4)
                .map(prefix -> prefix + Arbitraries.integers().between(100, 999).sample()),
            Arbitraries.integers().between(1, 50),
            Arbitraries.bigDecimals().between(BigDecimal.ONE, new BigDecimal("1000")).ofScale(2)
        ).as(OrderItem::new);
    }

    @Property
    void orderTotalEqualsItemSum(@ForAll("validOrders") Order order) {
        BigDecimal expectedTotal = order.getItems().stream()
            .map(item -> item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);

        Assertions.assertThat(order.calculateTotal().getAmount())
            .isEqualByComparingTo(expectedTotal);
    }
}

The @Provide method name matches the string in @ForAll("validOrders").

Arbitraries API Reference

Common builder methods:

// Integers
Arbitraries.integers().between(1, 100)
Arbitraries.integers().greaterOrEqual(0)

// Strings
Arbitraries.strings().alpha()           // a-zA-Z only
Arbitraries.strings().numeric()         // 0-9 only
Arbitraries.strings().ofLength(10)
Arbitraries.strings().withChars("abc")

// From fixed set
Arbitraries.of("red", "green", "blue")
Arbitraries.of(MyEnum.values())

// Collections
someArbitrary.list().ofMinSize(1).ofMaxSize(10)
someArbitrary.set().ofSize(5)
someArbitrary.array(String[].class)

// Combine multiple arbitraries
Combinators.combine(arbA, arbB, arbC).as((a, b, c) -> new MyObject(a, b, c))

// Filter (use sparingly — can slow generation)
Arbitraries.integers().filter(n -> n % 2 == 0)

Assumptions

When a property only makes sense for a subset of inputs, use Assumptions.assumeThat():

@Property
void divisionInverse(@ForAll double x, @ForAll double y) {
    Assumptions.assumeThat(y != 0.0);
    Assumptions.assumeThat(!Double.isNaN(x));
    Assumptions.assumeThat(!Double.isInfinite(x));

    double result = x / y * y;
    Assertions.assertThat(result).isCloseTo(x, Offset.offset(1e-10));
}

If assumeThat fails, jqwik discards that trial and tries again. If too many trials are discarded, jqwik warns you — which is a signal to constrain your generator directly rather than filtering via assumptions.

Understanding Shrinking

When jqwik finds a failing input, it tries to find a simpler input that still fails. This is shrinking. The goal is to give you the minimal failing case for debugging:

@Property
void noNegativeSumInList(@ForAll List<@Positive Integer> numbers) {
    int sum = numbers.stream().mapToInt(Integer::intValue).sum();
    // This property is false: [1, 1, ..., lots of numbers] can overflow
    Assertions.assertThat(sum).isGreaterThanOrEqualTo(0);
}

If jqwik finds that [1, 1, 1, ..., 2147483647] fails, it shrinks to [1, 2147483647], then to [2147483647], then to the simplest list that causes the overflow. The failure report shows both the original and the shrunk input.

To disable shrinking (for performance in CI):

@Property(shrinking = ShrinkingMode.OFF)
void noShrinkingHere(@ForAll String s) {
    // ...
}

Stateful Properties

jqwik supports stateful testing via @StatefulProperty — verifying that a sequence of operations on an object maintains invariants:

import net.jqwik.api.stateful.*;

class BoundedStackProperties {

    @Property
    void stackBehavior() {
        BoundedStackMachine machine = new BoundedStackMachine(10);
        new ActionSequence<>(machine)
            .withMaxTries(100)
            .run();
    }
}

class BoundedStackMachine implements StatefulTest<BoundedStack<Integer>> {

    private final int maxSize;

    BoundedStackMachine(int maxSize) {
        this.maxSize = maxSize;
    }

    @Override
    public BoundedStack<Integer> createModel() {
        return new BoundedStack<>(maxSize);
    }

    @Override
    public List<Action<BoundedStack<Integer>>> actions() {
        return List.of(
            new PushAction(),
            new PopAction(),
            new PeekAction()
        );
    }

    class PushAction implements Action<BoundedStack<Integer>> {
        @Override
        public boolean precondition(BoundedStack<Integer> stack) {
            return !stack.isFull();
        }

        @Override
        public BoundedStack<Integer> run(BoundedStack<Integer> stack) {
            int sizeBefore = stack.size();
            stack.push(Arbitraries.integers().sample());
            Assertions.assertThat(stack.size()).isEqualTo(sizeBefore + 1);
            return stack;
        }
    }

    class PopAction implements Action<BoundedStack<Integer>> {
        @Override
        public boolean precondition(BoundedStack<Integer> stack) {
            return !stack.isEmpty();
        }

        @Override
        public BoundedStack<Integer> run(BoundedStack<Integer> stack) {
            int sizeBefore = stack.size();
            stack.pop();
            Assertions.assertThat(stack.size()).isEqualTo(sizeBefore - 1);
            return stack;
        }
    }

    class PeekAction implements Action<BoundedStack<Integer>> {
        @Override
        public BoundedStack<Integer> run(BoundedStack<Integer> stack) {
            if (!stack.isEmpty()) {
                Integer top = stack.peek();
                Assertions.assertThat(stack.isEmpty()).isFalse();
                Assertions.assertThat(stack.peek()).isEqualTo(top); // peek is idempotent
            }
            return stack;
        }
    }
}

Configuring Run Count and Seeds

// Run 5000 times
@Property(tries = 5000)
void highCoverage(@ForAll String s) { /* ... */ }

// Fixed seed for reproducibility
@Property(seed = "42")
void deterministicRun(@ForAll int n) { /* ... */ }

// Use the failing seed from a previous run
// jqwik prints: "Property [propertyName] falsified. Seed: 12345678"
@Property(seed = "12345678")
void reproduceFailure(@ForAll String s) { /* ... */ }

When a property fails, jqwik prints the seed. You can use that seed to reproduce the exact same random sequence and debug the failure.

Combining with JUnit 5

jqwik runs alongside standard JUnit 5 tests. No special configuration:

@ExtendWith(SpringExtension.class)
@SpringBootTest
class UserServiceIntegrationTests {

    @Autowired
    private UserService userService;

    // Standard JUnit 5 test
    @Test
    void createUser_withValidData_succeeds() {
        var user = userService.create(new CreateUserRequest("test@example.com", "Alice"));
        assertThat(user.getId()).isNotNull();
    }

    // Property-based test in same class
    @Property(tries = 50)
    void createUser_validEmails_neverThrow(
            @ForAll @Email String email) {
        Assumptions.assumeThat(email.length() <= 255);
        assertThatCode(() -> userService.create(new CreateUserRequest(email, "Test")))
            .doesNotThrowAnyException();
    }
}

Common Mistakes

Over-using filter(): Filtering via Assumptions.assumeThat() or .filter() on generators discards invalid samples. If you discard >10% of samples, jqwik warns you. Generate constrained values directly instead.

Writing properties that are too weak: @Property void reverse(@ForAll String s) { assertThat(s).isNotNull(); } is trivially true and tests nothing. A property should capture a real invariant: round-trip, preservation, idempotence, ordering.

Not running on CI: Properties find bugs probabilistically. Running 1000 tries locally once isn't enough. Run them in CI so you get thousands of tries across many builds.

Ignoring the shrunk example: jqwik shows both the original failing input and the shrunk minimal input. The shrunk input is the one to debug — it's deliberately minimal.

Read more

Start now free