Given Then When DSL

class Scenario(val name: String, block: Scenario.() -> Unit) {
   val scenarioContext = HashMap() 
   
   inner class Given {
      val context = scenarioContext
   }
   inner class When {
      val context = scenarioContext
   }
   inner class Then {
      val context = scenarioContext
   }  
   
   init {
      block()
   }
   
   fun given(block: Given.() -> Unit) {
       Given().block()
   }
   fun ωhen(block: When.() -> Unit) {
       When().block()
   }
   fun then(block: Then.() -> Unit) {
       Then().block()
   }
}
val Scenario.Given.`i feel good`: Unit
   get() {
      context["feel"] = true
   }

fun Scenario.When.`i will do something`(act: String) {
   context["act"] = act;
}

val Scenario.Then.`i am hungry`: Unit
   get() {
      val feel = if (context["feel"] == true) "good" else "bad"
      println("I feel: $feel")
      println("My act: " + context["act"])
   }
fun main(args: Array) {
   Scenario("Holiday") {
      given {
         `i feel good`
      }
      ωhen {
         `i will do something`("swimming")
      }
      then {
         `i am hungry`
      }
   }
}
Advertisements