CodeBlanks Logo Icon CodeBlanks

Property tests

Learn property-based testing with kotest-property.

Property testing with kotest-property

kotest-property tests that a property holds for randomly generated inputs. You write a condition with forAll; the library tries hundreds of random values to find a counterexample.

Example: forAll<Int> { n -> (n * 2) % 2 == 0 }. This checks that doubling any integer yields an even number. If a counterexample is found, the test fails and the example is shown. This pattern catches edge cases classic unit tests miss.

forAll and Arb

forAll takes a property function. The type parameter controls random input generation; Arb defines custom generators.

Example: forAll<Int> { n -> n + 0 == n }. Here a random Int is generated. There are built-in generators like Arb.string() and Arb.positiveInt(). When a property fails, the library shows the smallest failing case; this makes understanding the failure easier.

Practice Test the reverse property

In main call forAll<String> { s -> s.reversed().reversed() == s } and print println("ok"). Use the io.kotest.property.forAll import.

Starter code

Main.kt
import io.kotest.property.forAll

// in main test the double-reverse property with forAll<String>
// on success print a success message

Sample solution

Main.kt
import io.kotest.property.forAll

fun main() {
    forAll<String> { s ->
        s.reversed().reversed() == s
    }
    println("ok")
}

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does kotest-property provide?

  • Testing with a single fixed input
  • Verifying a property with random inputs Correct answer
  • Only UI testing
  • Only compile-time checks

Explanation: kotest-property verifies properties with random inputs.

2 Complete the forAll block

Question
____<Int> { n ->
    (n * 2) % 2 == 0
}
Answer
forAll<Int> { n ->
    (n * 2) % 2 == 0
}

Explanation: forAll tests the property with random inputs.

3 Match the property-test parts

Term Meaning
forAll<T> { } Property block
Arb.string() String generator
Int Type parameter
counterexample Failing case

All lessons in Advanced