Kotlin

Lesson 10

Kotest fixtures and assertions

Write Kotlin tests that name the behavior, input fixture, and exact output contract.

Good Code

src/test/kotlin/reviews/ReviewValidatorTest.kt
class ReviewValidatorTest : StringSpec({
    "rejects a blank title" {
        // The fixture names the invalid input and expected error code.
        val result = validate(ReviewInput(title = " ", score = 5))

        result shouldBe ValidationError("title_blank")
    }
})

Bad Code

ReviewValidatorTest.kt
class ReviewValidatorTest : StringSpec({
    "validates reviews" {
        // Non-null assertion misses the validation contract callers use.
        validate(ReviewInput(title = "", score = 5)) shouldNotBe null
    }
})

Review Notes

What to review

Good Code

The good version gives the invalid input and expected error code, so a validation regression fails at the rule being protected.

Bad Code

The bad version only checks for a non-null result. It can pass while the validator returns the wrong error.

Takeaways

  • Kotlin tests should assert the result shape that callers depend on, not only that a function returned a value.