Tuesday, January 4, 2011

Running a JUnit 4 test from a Scala script

I'm using Scala now and then as a language for side projects. One of the nice things about Scala is that you can bootstrap with a single-file script, similar to Python or Ruby. Since I enjoy building things with test-driven development, it's not long after I write a script that I want to start writing tests for classes and functions. However, when I tried to do this in the straight-forward way, it doesn't quite work. Herein, the problem, and its solution.

As a first attempt, I expected this to work:

However, running this produces a failure in the infrastructure:

What's going on here is that when scala is run in single-file script mode, it implicitly wraps all of the declarations within the declaration of an anonymous singleton object (Main$$anon). When JUnit tries to reflectively create an ArithmeticTest object, it runs into the fact that, from the Java perspective, ArithmeticTest is a non-static inner class of Main$$anon. To get around this requires a bit of a dance, luckily made fairly short due to Scala's compact OO verbiage:

If I find myself doing this often, I imagine I'll be pulling this out into an importable library. Share and Enjoy.

No comments:

Post a Comment