Skip to content

Instantly share code, notes, and snippets.

@esuomi
Created May 26, 2013 18:27
Show Gist options
  • Save esuomi/5653614 to your computer and use it in GitHub Desktop.
Save esuomi/5653614 to your computer and use it in GitHub Desktop.
Got terribly carried over when doing something completely different so here ya go, example DSL for simple BDD style testing.
/**
* Very low-tech calculator.
*
* @author Esko Suomi <[email protected]>
* @since 26.5.2013
*/
class Calculator {
def sum(x:Int, y:Int) = { x + y }
}
/**
* Simple BDD-style testing suite test; Idea is to see how easy it is to define
* a DSL for doing simple things. Spoiler: Quite, although the Generics are a
* bit messy.
*
* For demonstration purposes running this class will fail.
*
* @author Esko Suomi <[email protected]>
* @since 26.5.2013
*/
object CalculatorTest extends App {
class Given[Context](given: => Context) {
def when[Expected](when: (Context) => Expected):Then[Context, Expected] = {
new Then[Context, Expected](given, when)
}
}
object Given {
def apply[Context](factory: => Context):Given[Context] = {
new Given[Context](factory)
}
}
class Then[Context, Expected](given: => Context, when: (Context) => Expected) {
def then(then: (Expected) => Boolean) = {
val result = when(given)
assume(then(result), "Got " + result) // lazy man's matcher
}
}
// here's a few tests:
Given { new Calculator } when { _.sum(2,2) } then { _ == 4 }
Given { new Calculator } when { _.sum(2,3) } then { _ == 5 }
// and one more complex one just for the sake of it
Given { new Calculator } when { calc => List(calc.sum(2,4), calc.sum(2,5)) } then { results =>
val x = for {
ex <- results.zip(List(6,8)) // herein lies error, 2+5 != 8
} yield ex._1 == ex._2
x.filter { _ != true }.isEmpty
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment