Property-based testing for booking and billing logic with Jqwik
Use Jqwik 1.9.3 and jqwik-kotlin to test invariants in booking and settlement logic, catching rounding and boundary bugs through automatic shrinking.
Our club’s fee-splitting logic passed every example-based test, yet real users still lost 1 won whenever a total didn’t divide evenly. Here is how I encoded domain invariants with Jqwik and used automatic shrinking to pinpoint both a rounding bug and a booking boundary bug.
Tested with Spring Boot 3.5.0, Kotlin 2.1.21, Jqwik 1.9.3 (including
jqwik-kotlin), JUnit 5.13.1, and Gradle Kotlin DSL.
Background
I maintain a study-room booking and fee-splitting service for a student club. Splitting a shared bill across attendees looked simple enough, so I wrote a handful of example-based tests like 10,000 / 4 = 2,500 and moved on. In production, though, splitting 10,000 across 3 people silently dropped 1 won—and the club treasurer caught the mismatch while reconciling the ledger.
Example-based tests only verify the inputs you think to write down. Property-based testing flips that workflow: you declare an invariant that must hold for every valid input—such as “the sum of all individual shares always equals the total”—and let the framework generate hundreds of inputs to hunt for a counterexample.
| Dimension | Example-based (@Test, @Example) | Property-based (@Property) |
|---|---|---|
| Inputs | Hand-picked values chosen by the developer | Generated values from an Arbitrary |
| What it checks | Expected output for a specific input | Invariants that hold across all valid inputs |
| Main strength | Clear executable specification; easy to read | Catches missed edge cases and input combinations |
| On failure | Reports the hardcoded input as-is | Shrinks the failing input to a minimal counterexample |
Property-based testing isn’t a fit everywhere. Running a test 1,000 times against an external HTTP API or a real database will make your suite slow and flaky. It’s also the wrong tool for UI copy or thin pass-through methods where you can’t state a clean mathematical or logical invariant. I restrict @Property tests to pure calculation and decision functions with no external I/O.
Project setup
Jqwik runs as an independent test engine on top of the JUnit Platform. If you’ve used Fixture Monkey before—which I wrote about in generating dummy data with Fixture Monkey—many of Jqwik’s Arbitrary concepts will feel familiar because Fixture Monkey builds on Jqwik under the hood.
The jqwik-kotlin module adds Kotlin-friendly generator extensions and nullable type support. Because Jqwik 1.9.3 is built against JUnit Platform 1.13.1, I bumped Spring Boot 3.5.0’s managed JUnit Jupiter version from 5.12.2 to 5.13.1 so both engines share the exact same platform version.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// build.gradle.kts
plugins {
id("org.springframework.boot") version "3.5.0"
id("io.spring.dependency-management") version "1.1.7"
kotlin("jvm") version "2.1.21"
kotlin("plugin.spring") version "2.1.21"
}
extra["junit-jupiter.version"] = "5.13.1"
dependencies {
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("net.jqwik:jqwik:1.9.3")
testImplementation("net.jqwik:jqwik-kotlin:1.9.3")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
kotlin {
compilerOptions {
freeCompilerArgs.addAll(
"-Xjsr305=strict",
"-Xnullability-annotations=@org.jspecify.annotations:strict",
"-Xemit-jvm-type-annotations", // Preserve type-use annotations in bytecode
)
javaParameters = true // Show real parameter names in failure reports
}
}
tasks.withType<Test> {
useJUnitPlatform {
includeEngines("jqwik", "junit-jupiter")
}
}
Don’t skip -Xemit-jvm-type-annotations: without it, Kotlin drops type-use constraint annotations like List<@AlphaChars String> from the compiled bytecode, and Jqwik silently ignores them.
Step 1. Turning settlement rules into properties
The original implementation simply took the integer quotient for every participant, dropping any remainder on the floor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/main/kotlin/com/example/club/settlement/SettlementCalculator.kt
package com.example.club.settlement
object SettlementCalculator {
// Before fix: fun split(total: Long, people: Int) = List(people) { total / people }
fun split(total: Long, people: Int): List<Long> {
require(total >= 0) { "Total amount must be non-negative." }
require(people > 0) { "Participant count must be at least 1." }
val base = total / people
val remainder = (total % people).toInt()
// Distribute the remainder by adding 1 unit to the first `remainder` participants.
return List(people) { index -> if (index < remainder) base + 1 else base }
}
}
I expressed the settlement rules as three invariants: the result length matches the participant count, the sum of shares equals the total, and the gap between the highest and lowest share never exceeds 1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// src/test/kotlin/com/example/club/settlement/SettlementPropertyTest.kt
package com.example.club.settlement
import net.jqwik.api.Arbitrary
import net.jqwik.api.ForAll
import net.jqwik.api.Property
import net.jqwik.api.Provide
import net.jqwik.api.constraints.LongRange
import net.jqwik.api.statistics.Statistics
import net.jqwik.kotlin.api.any
import org.assertj.core.api.Assertions.assertThat
class SettlementPropertyTest {
@Property
fun `sum of split shares always equals total`(
@ForAll @LongRange(min = 0, max = 10_000_000) total: Long,
@ForAll("peopleCounts") people: Int,
) {
Statistics.collect(if (total % people == 0L) "divisible" else "has-remainder")
val shares = SettlementCalculator.split(total, people)
assertThat(shares).hasSize(people)
assertThat(shares.sum()).isEqualTo(total)
assertThat(shares.max() - shares.min()).isLessThanOrEqualTo(1L)
}
@Provide
fun peopleCounts(): Arbitrary<Int> = Int.any(1..30)
}
When I ran this property against the buggy code, Jqwik didn’t just dump the first random failure it hit. It shrank the input down to the smallest case that still violated the assertion:
1
2
3
4
5
6
7
8
9
Shrunk Sample (5 steps)
-----------------------
total: 1
people: 2
Original Sample
---------------
total: 783421
people: 7
Seeing total = 1, people = 2 makes the remainder bug obvious in one second compared to 783421 / 7. The Statistics.collect output also confirmed that most generated inputs had a non-zero remainder—exposing the exact blind spot in my original hand-picked examples.
Step 2. Combining generators for booking boundary checks
The booking module’s core check is deciding whether two time slots overlap. We represent time as integer minutes elapsed since 9:00 AM.
1
2
3
4
5
6
7
8
9
10
11
// src/main/kotlin/com/example/club/reservation/TimeSlot.kt
package com.example.club.reservation
data class TimeSlot(val start: Int, val end: Int) {
init {
require(start < end) { "End time must be after start time." }
}
// Before fix: start <= other.end && other.start <= end
fun overlaps(other: TimeSlot): Boolean = start < other.end && other.start < end
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/test/kotlin/com/example/club/reservation/TimeSlotPropertyTest.kt
package com.example.club.reservation
import net.jqwik.api.Arbitrary
import net.jqwik.api.ForAll
import net.jqwik.api.Property
import net.jqwik.api.Provide
import net.jqwik.kotlin.api.any
import net.jqwik.kotlin.api.combine
import org.assertj.core.api.Assertions.assertThat
class TimeSlotPropertyTest {
@Property
fun `overlap detection is symmetric`(
@ForAll("slots") a: TimeSlot,
@ForAll("slots") b: TimeSlot,
) {
assertThat(a.overlaps(b)).isEqualTo(b.overlaps(a))
}
@Property
fun `back-to-back bookings do not overlap`(
@ForAll("slots") first: TimeSlot,
@ForAll("lengths") length: Int,
) {
val next = TimeSlot(first.end, first.end + length)
assertThat(first.overlaps(next)).isFalse()
}
@Provide
fun slots(): Arbitrary<TimeSlot> =
combine(Int.any(0..720), Int.any(10..180)) { start, length -> TimeSlot(start, start + length) }
@Provide
fun lengths(): Arbitrary<Int> = Int.any(10..180)
}
The second property failed immediately against the old code. Using <= treated a 10:00–11:00 booking and an 11:00–12:00 booking as conflicting. That single comparison operator turned out to be the exact cause of club members reporting they couldn’t book consecutive slots.
How generation, shrinking, and reproduction work
By default, every @Property method runs 1,000 tries. On each try, Jqwik resolves an Arbitrary for every parameter and intentionally mixes edge cases—such as 0, 1, and range minimums or maximums—into the stream of random values.
flowchart TD
A["Run @Property"] --> B["Generate inputs via Arbitrary"]
B --> C["Mix edge cases with random values"]
C --> D{"Property holds?"}
D -->|"Failure"| E["Shrink toward minimal counterexample"]
E --> F["Print report with seed"]
Shrinking works because Jqwik records how each value was constructed, then walks those steps backward to test simpler values while verifying that the property still fails. Because TimeSlot was built with combine, Jqwik shrinks both start and length independently and produces a minimal composite object. The default ShrinkingMode.BOUNDED caps shrinking at 10 seconds and reports the smallest counterexample found within that budget.
Every failure report prints the random seed used for that run. Under the default AfterFailureMode.SAMPLE_FIRST, your very next test run replays the last failing sample first, so you get instant feedback after fixing the bug. To reproduce a failure on another machine, pass the reported value into @Property(seed = "...").
Overusing
filteron anArbitrarycauses Jqwik to throwTooManyFilterMissesExceptionwhen it can’t generate enough valid samples. Also watch out for a Kotlin import collision: importingnet.jqwik.api.constraints.IntRangeclashes withkotlin.ranges.IntRange, so I prefer expressing integer ranges in@Providemethods withInt.any(1..30)instead.
Summary
Property-based testing didn’t replace our example-based tests—it covered the inputs I failed to imagine. Those same properties now act as guardrails whenever the settlement or booking rules change. Here is the checklist I use when adding Jqwik to a domain module:
- Isolate the target calculation or decision logic into a pure function with no external I/O.
- Write down input-independent invariants (“sum preserved”, “symmetric”, “exclusive boundary”) before coding generators.
- Verify generated input distribution with
Statistics.collect. - Align JUnit Jupiter and Jqwik on the same JUnit Platform version.
- Capture the reported
seedand shrunk counterexample as a permanent@Exampleregression test.