jastrachan | 13 Jul 11:11 2004

[groovy-dev] Bruce Eckel's talk & easier unit testing...

While watching Bruce Eckel's talk


it got me thinking that it'd be really cool to be able to type 
something like the following and use it as a unit test case...

     foo = new Foo(123)
     assert foo.cheese == "cheddar"

i.e. just write a chunk of code as being an individual unit test case. 
This works fine for real simple stuff - if you want to get complex, 
write a class with setUp() / tearDown() methods and the like. The 
tricky thing is the above script won't generate a class which is-a 
JUnit TestCase and so if this were compiled to bytecode the usual JUnit 
test runner tools might not pick it up.

I'm wondering if this actually matters. e.g. we could run this from the 
command line whenever we like...

groovy MyTest.groovy

and if we get any exceptions, then its failed :). In this case the 
script = 1 test, so there's no real need to use a TestCase etc. So 
maybe we could have a form of the Ant <junit> task which as well as 
looking for TestCase instances, could also gracefully handle scripts as 
above, which would all implement Runnable, so we just treat the run() 
method as one test etc.

Though writing all that plumbing & hacking of Ant tasks doesn't sound 
like fun. So another idea could be to somehow mutate the script to be 
derived from TestCase, using some magic mechanism. e.g. if we supported 
AST level macros, we could maybe use a macro to change the base class 
of the script such that it actually created a TestCase with a main 
which ran the script. I guess that'd be the ideal, then it really 
would, at the bytecode level, be a TestCase and so work with any JUnit 
capable code. I'm not sure yet what the macro should look like but 
imagine its something like...

     use UnitTest
     foo = new Foo(123)
     assert foo.cheese == "cheddar"

or to looky-likey Java 5

      <at> UnitTest
     foo = new Foo(123)
     assert foo.cheese == "cheddar"