Kotest Konform Matchers
Konform matchers can be used in tests to check whether a specified object passes or fails validation.
Kotest provides various matchers that can be used with Konform. These matchers can be used in tests to check whether a specified object passes or fails validation.
To use these matchers, add the io.kotest.extensions:kotest-assertions-konform:<version> implementation to your build. This module is available for both JVM and JS targets.
Start with a basic data class:
data class UserProfile(
val fullName: String,
val age: Int?
)
Then given the following user profile validator:
val validateUser = Validation<UserProfile> {
UserProfile::fullName {
minLength(4)
maxLength(100)
}
UserProfile::age ifPresent {
minimum(21)
maximum(99)
}
}
You can test whether an instance passes validation like this:
val alice = UserProfile("Alice", 25)
validateUser shouldBeValid alice
And you can test whether an instance fails validation with specific error messages like this:
val bob = UserProfile("bob", 18)
validateUser.shouldBeInvalid(bob) {
it.shouldContainError(UserProfile::fullName, "must have at least 4 characters")
it.shouldContainError(UserProfile::age, "must be at least '21'")
}
| Matcher | Description |
|---|---|
validation.shouldBeValid(value) |
Checks that validation is valid for the given value. |
validation.shouldBeInvalid(value) |
Checks that validation is invalid for the given value. |
validation.shouldBeInvalid(value) { block } |
Checks that validation is invalid for the given value and runs the block with the invalid value. |