Skip to content

Instantly share code, notes, and snippets.

@cvogt
Last active August 29, 2015 14:22
Show Gist options
  • Save cvogt/a46318bc1cfb75fc1f35 to your computer and use it in GitHub Desktop.
Save cvogt/a46318bc1cfb75fc1f35 to your computer and use it in GitHub Desktop.
No-magic Scala test framework concept
// admittedly there is some optional implicit magic below to reduce some boiler place,
// but it is only using implicits, not runtime reflection as many test frameworks do
// usage: stand-alone test
object MyTest extends Test(
assert(2 == 1+1)
)
// usage: test suite
object MySuite extends TestSuite(
test{ // anonymous test
assert(2 == 1+1)
},
test("my test"){ // named test
assert(2 == 1+1)
},
"my test"{ // optional magic String#apply extension method
assert(2 == 1+1)
},
// optional magic conversion for anonymous test
assert(2 == 1+1)
)
// usage: test suite
// Framework
object assert{
/**
value capturing assert macro as in Scala Test for better error messages
admittedly this is magical, but not in terms of semantics, only in terms of better error messages
*/
def apply(expr: => Boolean): Unit = macro ...
}
trait Test{
def main(args: Array[String]): Unit
}
case class TestCase(name: String)(val code: => Unit) extends Test{
def this(code: => Unit) = this(this.getClass.getSimpleName)(code)
def main(args: Array[String]) = code
}
object test{
def apply(name: String)(val code: => Unit) = TestCase(name)(code)
def apply(code: => Unit) = TestCase(code)
}
abstract class TestSuite(tests: Test*) extends Test{
def main(args: Array[String]) = tests.foreach{
test => try{
test.main(Array())
} catch {
case e:AssertionError => TestLogger.failure(e)
case e:Exception => TestLogger.exception(e)
}
}
}
/** optional implicit magic to save 6 chars per test if really wanted */
implicit class StringTestExtensions(name: String){
def apply(code: => Unit) = test(name)(code)
}
/** optional implicit magic to save 6 chars per test if really wanted */
implicit object UnitToTest{
def apply(code: => Unit) = test(code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment