Dev

Generating test data with Fixture Monkey in Kotlin

Use Fixture Monkey 1.1 to generate Kotlin registration requests from Jakarta Validation constraints and share the fixtures across Gradle tests.

Generating test data with Fixture Monkey in Kotlin

A shared data.sql file worked for a handful of Spring tests. I switched to Fixture Monkey when I needed to generate registration requests from the same Jakarta Validation constraints that the application uses.

The examples use Fixture Monkey 1.1.11, Kotlin, Gradle Kotlin DSL, and Jakarta Bean Validation.

When a static fixture starts getting in the way

I used to put test data in data.sql. Spring can load the predefined rows when the application starts, so there’s little setup to write. The inconvenience starts when several tests depend on the same records. A change meant for one scenario can break another, and the test itself offers no clue which columns came from the SQL file.

I found Naver’s Fixture Monkey while looking for a way to generate Java and Kotlin objects at the point where a test needs them. The Jakarta Validation plugin reads supported annotations such as @NotNull, @Size, and @Pattern and builds generators around the constraints. The Jqwik plugin supplies the underlying value generators. That makes it possible to exercise a wider range of valid inputs without recording every permutation by hand.

ApproachGood fitConstraint
data.sqlA stable set of rows for a database scenarioShared records can couple otherwise unrelated tests
Explicit buildersBoundary cases and cases where each value mattersRepeated setup grows with the number of fields
Fixture MonkeyPopulating fields that don’t drive the assertionGenerated variation needs a replay path when a test fails

For a duplicate-email test, I would still choose the duplicate explicitly. The generator can fill in the phone and name. Keeping the value under test visible makes the failure easier to understand.

Put reusable builders in Gradle’s test fixtures

Gradle’s java-test-fixtures plugin adds a fixture source set that tests can use without putting test helpers in production code. In a Kotlin JVM project, I put the builders under src/testFixtures/kotlin and declare their dependencies with testFixturesImplementation. Since the callers only need a RegisterRequest, the Fixture Monkey types can stay inside the fixture object. Gradle test fixtures documentation

build.gradle.kts

1
2
3
4
5
6
7
8
9
plugins {
    id("java-test-fixtures")
}

dependencies {
    val fixtureMonkeyVersion = "1.1.11"
    testFixturesImplementation("com.navercorp.fixturemonkey:fixture-monkey-starter-kotlin:$fixtureMonkeyVersion")
    testFixturesImplementation("com.navercorp.fixturemonkey:fixture-monkey-jakarta-validation:$fixtureMonkeyVersion")
}

The Kotlin starter supplies Kotlin-aware construction and the Jqwik integration used here. The separate Jakarta module connects Bean Validation annotations to generation. Keep the artifacts on the same version so that the plugins load against the matching core APIs.

Build one generator for the registration request

I assemble the generator once in UsersFixture. KotlinPlugin() handles Kotlin types, SimpleValueJqwikPlugin() provides Jqwik-backed values, and JakartaValidationPlugin() applies supported Jakarta constraints. giveMe(size) returns a list for a batch test, while giveMeOne() is enough when a test needs a single request.

src/testFixtures/kotlin/UsersFixture.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import com.navercorp.fixturemonkey.FixtureMonkey
import com.navercorp.fixturemonkey.api.plugin.SimpleValueJqwikPlugin
import com.navercorp.fixturemonkey.jakarta.validation.plugin.JakartaValidationPlugin
import com.navercorp.fixturemonkey.kotlin.KotlinPlugin
import com.navercorp.fixturemonkey.kotlin.giveMe
import com.navercorp.fixturemonkey.kotlin.giveMeOne

object UsersFixture {
    private val fixtureMonkey: FixtureMonkey = FixtureMonkey.builder()
        .plugin(KotlinPlugin())
        .plugin(SimpleValueJqwikPlugin())
        .plugin(JakartaValidationPlugin())
        .build()

    fun getRandomRegisterRequest(size: Int): List<RegisterRequest> {
        return fixtureMonkey.giveMe(size)
    }

    fun getRandomRegisterRequest(): RegisterRequest {
        return fixtureMonkey.giveMeOne()
    }
}

The builder becomes the test’s Arrange step. The test can get a request and focus on the operation and assertion. If a fixture is used by several test classes, put stable domain defaults in the fixture and keep scenario-specific overrides at the call site.

Generate valid signup data

The DTO maps annotations to the backing fields with Kotlin’s @field: target. It constrains the email format and length, phone format, name, and password. Example values in @Schema describe the API. Fixture Monkey derives its constraints from the validation annotations. The phone and name patterns below belong to this API’s input format.

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
39
40
41
42
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Pattern
import jakarta.validation.constraints.Size

/** Registration request */
@Schema(description = "Registration request")
data class RegisterRequest(
    /** Email */
    @field:Schema(description = "Email", example = "test12345@test.com")
    @field:Size(max = 254, message = "Email must be at most 254 characters")
    @field:Pattern(
        regexp = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
        message = "Enter a valid email address",
    )
    val email: String,
    /** Phone number */
    @field:Pattern(
        regexp = "^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}\$",
        message = "Enter a valid phone number",
    )
    @field:Schema(description = "Phone number", example = "010-1234-5678")
    @field:NotNull(message = "Enter a phone number")
    val phone: String,
    /** Name */
    @field:Schema(description = "Name", example = "Example")
    @field:NotBlank(message = "Enter a name")
    @field:Pattern(
        regexp = "^[\uAC00-\uD7A3a-zA-Z]{2,10}\$",
        message = "Use Korean or English letters in the name",
    )
    val name: String,
    /** Password */
    @field:Schema(description = "Password", example = "Password1234~!")
    @field:NotBlank(message = "Enter a password")
    @field:Pattern(
        regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{5,}\$",
        message = "Use at least 5 characters, with uppercase and lowercase letters, a digit, and punctuation",
    )
    val password: String,
)
AnnotationConstraint
@NotBlankA string has a value and contains a non-whitespace character
@NotNullA value is present
@SizeA string or collection stays within the configured length or size
@PatternA string matches the supplied regular expression

To inspect a sample, I print three requests with a small prettyJson() extension. That extension is local to the project, so use your project’s JSON serializer if you don’t have it.

1
2
3
println(
    UsersFixture.getRandomRegisterRequest(3).prettyJson(),
)

The generated output varies by run. This sample shows a mix of email lengths, phone formats, and passwords. The name examples use ASCII letters from the same range allowed by the DTO.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[ {
  "email" : "JD_PJfkJPEUPugIC%STbwvIA9emM@pBYfF4vxOVPJATLMUTZ7uJdxE628L9HPbAAtbbu.ZKKZxqtK",
  "phone" : "010-711-9539",
  "name" : "ValidName",
  "password" : "e@?H{n L\\#rWlsT^PM23\"#RQUS/@iEK;\"kW@poS\\[$,yMsc52_<peT d2p`E5am(2}QgZTXTpj,'K(rX~O:C=ffBvE'HJ63sq<AFZ.FL Uw%k\"b&=5c@s,;WYjn5{B,Vijx]p8 q4T8K);[q%c,`}4BT'&qoo}_FY!W8/4Ej6i!+~!te`Ho;{364TJmK,-PqdIM-=:D@>F~&)26pW'S\\9\"5TG21/&;N8lM=ZS%`}R\\ @t1AaL^;kBVx_|A*ioW;-O[*2!Y|s=E'_$7M1|)5Yu8O}9A5,/8O:AQ`,|Z^bR^Tn`L=u+c"
}, {
  "email" : "ZJTxPio0khu6E+FGagD5wMmGitx.K1TTPQ.d2c_+KN+azf3gI049pZNuVI_E0UHR%5tJJBOv.@nEk7DUqAeUgHYMPIu1SyDrUKbtly2B3G3s5CN7QiFLU0b8rtbDIK699swITAt2sO.qSdjH4IxyRtdn4ZI2iwQ.QfpaZlctB",
  "phone" : "010-997-3963",
  "name" : "SamTest",
  "password" : "YcYA.n'FR`[>5per7|sNneO7!@K~u]9MgB&p0[ !q=H.F'i\"Y/Qa*]^ip28c'\\qsn^XZ34X(()PX&NEF!D` qQQxo>\\EA9&:3n*/gO!)# L1DAb{IxmH~.1{.+]5aQ>\\qH]>x&`}j3!(myqplYT7DK/Qm-A?dHqff`R`OZGg)F*7/H.srQ\"AXN0skCx_|7<~=LmT~a\"_V\\yyAzlMa'>PQg/EuwIU],p-^|t'D[#F'N\\A:.oF<`I8rIoNPzvKH.8ye`<7Y={<<K8KO>T \"fo}K:KPo1ScKB'"
}, {
  "email" : "R.0km.5@2oNfdzWLQdrMJBQ2Wn4TtFerKFfhzW2YrmuvgwKI.NfIokRDuBlbjkaESlQWEJJsllVlhrkUrGUjdhKcMNRPjoeuuhPuAUrImiNWlnZswiPSWYGvmzFIkxKcdUJFIas",
  "phone" : "010-024-9565",
  "name" : "Oak",
  "password" : "[7RyTr!anY8oj|@xkx`:z5EXP YpI)v}+Bm$2nn7l+.f44Ce#-r6|,IrQ]Jcrc.dO9xX8x6/Ait)lx:4k29*:/TNnf]w+s\"!E!c^<W1bE}87_JiZ>|7q0,bHDns hwv<\"A$+o}whNH()&LHAQmaAJUG!m/C92dhH.p5Vc2m=GSWC7yM==:m(-`4};&y8XK|m;iH{eVlnF:\"J%C='=X`~eMWB+@3 []r]Qv-:.sL~rj54HAcR[lM>MdZqmyE#y*zi57_G(/8ptMnX`$Bqp4\\$\\f\\3-yW6K#O#[-}.}ga%EY(n\\CJ:rb'"
} ]

Keep random fixtures useful in tests

Generated values make unexpected combinations easier to find, especially once tests have grown beyond the examples in data.sql. A fixture generator does not know that an email must be unique in the database or that a start date must precede an end date. Put those relationships in the fixture builder or spell them out in the test.

  • Validate a small generated batch with the same Jakarta validator as the application before relying on it in integration tests.
  • Set exact values for boundaries, duplicate identifiers, and failure cases that carry meaning in the assertion.
  • Capture the failing input or the property test seed so a randomized failure can be replayed.
  • Keep stable database reference data in a deterministic setup when multiple tests need that specific data.

The follow-up on advanced Kotlin fixtures covers rules that depend on more than one field.

References

This post is licensed under CC BY 4.0 by the author.