Designing domain test data with Fixture Monkey Kotlin and Jqwik
Combine Fixture Monkey 1.1.12 KotlinPlugin, Jakarta Validation, giveMeKotlinBuilder, and Jqwik combine to generate valid domain data with shrinking.
In my earlier post on generating dummy data with Fixture Monkey, I covered generating random objects that respect Bean Validation annotations. This post tackles the next hurdle: enforcing cross-field domain rules with Fixture Monkey’s Kotlin builder API and combining it with Jqwik so property-based shrinking still works.
Tested with Fixture Monkey 1.1.12, Jqwik 1.9.3, Kotlin 2.1.21, Spring Boot 3.5.0, and JUnit 5.13.1.
Background
Once I added Fixture Monkey to our club’s study-room reservation API, generating request DTOs became straightforward—until cross-field domain rules got in the way. headCount stayed between 1 and 10 and participantIds held 1 to 10 items, satisfying every individual annotation, yet almost every sample violated the rule that participantIds.size must equal headCount. I ended up patching objects with .copy(...) in every test, which defeated the purpose of randomized fixtures.
To stop fighting the tools, I mapped out where each approach fits:
| Approach | Best fit | Limitations |
|---|---|---|
giveMeOne<T>() | Tests that only need any valid object regardless of field values | Cannot enforce cross-field domain rules |
giveMeKotlinBuilder + setExp/sizeExp | Pinning specific fields to highlight a test scenario | Pinning too many fields becomes no better than manual construction |
thenApply | Deriving one field’s value or size from another sampled field | Samples twice internally, so it’s slower |
Jqwik combine + Fixture Monkey | Boundary testing and shrinking on key fields while auto-filling the rest | Most setup overhead |
| Hand-written factory function | Small value objects with 3–4 fields | Every new field forces updates across test factories |
Fixture Monkey isn’t always the right choice. For small value objects with three or four fields, calling the constructor directly is clearer and faster. Randomized fixtures also get in the way of response snapshot tests that expect deterministic output, or validation tests that assert exact error messages on specific invalid inputs.
Project setup
Just like in property-based testing for booking and billing logic with Jqwik, I separated shared fixtures using Gradle’s java-test-fixtures plugin and added Jqwik alongside jqwik-kotlin. fixture-monkey-starter-kotlin already brings in the Jakarta Validation plugin transitively.
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
// 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"
id("java-test-fixtures")
}
extra["junit-jupiter.version"] = "5.13.1"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-validation")
testFixturesApi("com.navercorp.fixturemonkey:fixture-monkey-starter-kotlin:1.1.12")
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", "-Xemit-jvm-type-annotations")
javaParameters = true
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Here are the request DTO and the reservation policy we want to test:
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
// src/main/kotlin/com/example/club/reservation/ReservationRequest.kt
package com.example.club.reservation
import jakarta.validation.Valid
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.Max
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern
import jakarta.validation.constraints.Size
data class ReservationRequest(
@field:NotBlank @field:Size(max = 20) val roomName: String,
@field:Min(1) @field:Max(10) val headCount: Int,
@field:Min(30) @field:Max(240) val durationMinutes: Int,
@field:NotBlank @field:Email val contactEmail: String,
@field:Valid val host: Host,
@field:Size(min = 1, max = 10) val participantIds: List<Long>,
)
data class Host(
@field:NotBlank @field:Size(max = 10) val name: String,
@field:Pattern(regexp = "^\\d{9}$") val studentId: String,
)
object ReservationPolicy {
const val ROOM_CAPACITY = 10
fun violations(request: ReservationRequest): List<String> = buildList {
// Before fix: request.headCount >= ROOM_CAPACITY
if (request.headCount > ROOM_CAPACITY) add("Room capacity exceeded.")
if (request.participantIds.size != request.headCount) add("Participant count does not match headCount.")
if (request.durationMinutes % 30 != 0) add("Reservations must be in 30-minute increments.")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/testFixtures/kotlin/com/example/club/fixture/ClubFixtures.kt
package com.example.club.fixture
import com.navercorp.fixturemonkey.FixtureMonkey
import com.navercorp.fixturemonkey.jakarta.validation.plugin.JakartaValidationPlugin
import com.navercorp.fixturemonkey.kotlin.KotlinPlugin
object ClubFixtures {
val fixtureMonkey: FixtureMonkey = FixtureMonkey.builder()
.plugin(KotlinPlugin())
.plugin(JakartaValidationPlugin())
.defaultNotNull(true)
.build()
}
Step 1. Pinning scenarios with the Kotlin builder
giveMeKotlinBuilder provides setExp, sizeExp, and setPostCondition, all accepting Kotlin property references. Using Host::name instead of a raw string path like "host.name" means a renamed property fails at compile time rather than silently breaking a test at runtime.
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
// src/test/kotlin/com/example/club/reservation/ReservationFixtureTest.kt
package com.example.club.reservation
import com.example.club.fixture.ClubFixtures.fixtureMonkey
import com.navercorp.fixturemonkey.kotlin.giveMeKotlinBuilder
import com.navercorp.fixturemonkey.kotlin.into
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class ReservationFixtureTest {
@Test
fun `fills remaining fields within constraints after pinning scenario values`() {
val request = fixtureMonkey.giveMeKotlinBuilder<ReservationRequest>()
.setExp(ReservationRequest::headCount, 4)
.sizeExp(ReservationRequest::participantIds, 4)
.setExp(ReservationRequest::host into Host::name, "Namju Kim")
.setPostCondition<Int>(ReservationRequest::durationMinutes) { it % 30 == 0 }
.sample()
assertThat(request.host.name).isEqualTo("Namju Kim")
assertThat(ReservationPolicy.violations(request)).isEmpty()
}
@Test
fun `aligns participant list size to the sampled headCount`() {
val request = fixtureMonkey.giveMeKotlinBuilder<ReservationRequest>()
.setPostCondition<Int>(ReservationRequest::durationMinutes) { it % 30 == 0 }
.thenApply { sampled, builder -> builder.size("participantIds", sampled.headCount) }
.sample()
assertThat(request.participantIds).hasSize(request.headCount)
}
}
Watch out for setPostCondition: it acts as a retry filter that keeps resampling until the predicate passes. Between 30 and 240, only 8 values are multiples of 30, so filtering causes frequent retries. Whenever you know the valid set upfront, passing a value directly with setExp is much faster.
Step 2. Combining Fixture Monkey with Jqwik properties
My first attempt was returning giveMeKotlinBuilder<T>().build() directly from a Jqwik @Provide method, since build() returns a Jqwik Arbitrary<T>. That compiled and ran, but when a property failed, Jqwik couldn’t shrink the counterexample at all. I’ll explain why in the next section; first, here is the pattern that actually works. I let Jqwik’s combine generate the fields that drive business rules, and let Fixture Monkey fill in the rest. For Jqwik setup and shrinking fundamentals, see property-based testing for booking and billing logic with Jqwik.
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
// src/test/kotlin/com/example/club/reservation/ReservationPolicyPropertyTest.kt
package com.example.club.reservation
import com.example.club.fixture.ClubFixtures.fixtureMonkey
import com.navercorp.fixturemonkey.kotlin.giveMeKotlinBuilder
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 ReservationPolicyPropertyTest {
@Property(tries = 200)
fun `valid reservation requests produce no policy violations`(
@ForAll("validRequests") request: ReservationRequest,
) {
assertThat(ReservationPolicy.violations(request)).isEmpty()
}
@Provide
fun validRequests(): Arbitrary<ReservationRequest> =
combine(Int.any(1..10), Int.any(1..8)) { headCount, slots ->
fixtureMonkey.giveMeKotlinBuilder<ReservationRequest>()
.setExp(ReservationRequest::headCount, headCount)
.sizeExp(ReservationRequest::participantIds, headCount)
.setExp(ReservationRequest::durationMinutes, slots * 30)
.sample()
}
}
This test failed on its very first run. Jqwik injected the upper boundary 10 from Int.any(1..10) into its samples and shrank the failure straight down to headCount = 10. Our policy had headCount >= ROOM_CAPACITY instead of >, rejecting reservations that filled the room to exact capacity. Pure random Fixture Monkey runs rarely hit 10 on a single test invocation, so that off-by-one bug had gone unnoticed.
How it works under the hood
Fixture Monkey doesn’t instantiate objects directly. It first inspects the target type to build a property tree, then attaches generation and validation rules to each node.
flowchart TD
A["Call giveMeKotlinBuilder"] --> B["KotlinPlugin inspects primary constructor"]
B --> C["Map Jakarta constraints to value ranges"]
C --> D["Apply setExp and sizeExp rules"]
D --> E["Instantiate via primary constructor"]
E --> F["Validate and retry on failure"]
KotlinPlugin uses PrimaryConstructorArbitraryIntrospector first so data class primary constructor parameters are recognized as properties. JakartaValidationPlugin translates annotations like @Size, @Min, @Pattern, and @Email into generation constraints via JakartaValidationConstraintGenerator, then runs JakartaArbitraryValidator over the constructed instance. If validation or setPostCondition fails, Fixture Monkey retries up to generateMaxTries.
Now for why .build() broke shrinking: in Fixture Monkey 1.1.12, DefaultArbitraryBuilder.build() wraps generation inside Arbitraries.ofSuppliers { ... }. From Jqwik’s perspective, an ofSuppliers arbitrary is an opaque supplier function—it has no visibility into the internal fields and therefore no way to shrink them. By contrast, when headCount and slots come from Jqwik’s combine, Jqwik tracks how those integers were generated, so both boundary injection and shrinking work as expected.
Fixture Monkey 1.1.x transitively depends on Jqwik 1.7.3. Declaring Jqwik 1.9.3 explicitly lets Gradle resolve the higher version, but verify the resolved classpath with
./gradlew dependencyInsight --dependency net.jqwik:jqwik-api --configuration testRuntimeClasspath. Also note that unpinned fields insidecombineare re-randomized by Fixture Monkey on every shrinking step. If a failure depends on an unpinned field, the counterexample can drift—fix it by settingFixtureMonkey.builder().seed(...)to reproduce the exact sample.
Summary
Splitting responsibilities cleanly—Fixture Monkey for filling valid background fields, Jqwik for exploring boundaries and shrinking key domain inputs—lets both tools play to their strengths without overlapping. Here is the checklist I use when setting up domain fixtures:
- Avoid using plain
giveMeOnefor objects that carry cross-field domain invariants. - Prefer type-safe Kotlin property references (
setExp,sizeExp,into) over raw string paths. - Replace low-hit-rate
setPostConditionfilters with directsetExpassignments. - Drive key rule-bearing fields through Jqwik
combineso boundary injection and shrinking stay intact. - Check the resolved Jqwik version and pin a Fixture Monkey seed when debugging non-deterministic failures.