1

I am still new to Kotlin and Kotest and I am struggling of finding a way to create a BDD style of test. My problem is how the framework enables to create reusable Given step. For example:

class KotestTest1 : BehaviorSpec({
    given("State A") {
        // Verify the State A exists
        println("Verify the State A exists")
        `when`("Action A") {
            // Execute Action A
            println("Execute Action A")
            then("State => A1") {
                // Verify the state is now A1
                println("Verify the state is now A1")
            }
        }
    }
})


class KotestTest2 : BehaviorSpec({
    given("State A") {
        // Verify the State A exists
        println("Verify the State A exists")
        `when`("Action B") {
            // Execute Action B
            println("Execute Action B")
            then("State => B1") {
                // Verify the state is now B1
                println("Verify the state is now B1")
            }
        }
    }
})

So here I have code repetition for Given step "State A". I am wondering how would be the intended way of creating the whole step. It looks like given(description: String) is something I have to repeat and for println("Verify the State A exists") I just extract it to common function.

I wish I could structure my code better that I could create Given steps and use them in multiple test scenarios. Any suggestions on that?

Juhan
  • 11
  • 1

1 Answers1

2

I think the most usual approach to these would be to merge both tests into a single one, and have nested tests there:

class KotestTest : BehaviorSpec({
    Given("State A") {
        When("Action A") {
            Then("State => A1") {

            }
        }
        When("Action B") {
            Then("State => B1") {
                
            }
        }
    }
})
LeoColman
  • 6,950
  • 7
  • 34
  • 63