I like writing unit tests but Java doesn’t make it particularly easy. Especially if you need to create objects and object trees, transform objects for checking them etc. I miss a lot a conscise, powerful syntax, literals for regular expressions and collections, conscise, clojure-based methods for filtering and transforming collections, asserts providing more visibility into why they failed. But hey, who said I have to write tests in the same language as the production code?! I can use Groovy – with its syntax being ~ 100% Java + like thousand % more, optional usage of static/dynamic typing, closures, hundreds of utility methods added to the standard JDK classes and so on. Groovy support for example in IntelliJ IDEA (autocompletion, refactoring …) is very good so by using it you loose nothing and gain incredibly much. So I’ve decided that from now on I’ll only use Groovy for unit tests. And so far my experience with it was overwhelmingly positive (though few things are little more complicated by the positives more than compensate for them). Read on to find out why you should try it too.
(The arguments here focus on Groovy but I guess similar things could be said about JRuby, Scala etc. – with the exception of Java code compatibility, which you only get in Groovy.)
Few examples
Some of the example below use some Groovy magic but don’t be scared. You can write Groovy just as if it was Java and only learn and introduce its magic step by step as you need it.
Bean construction:
def testBean = new Customer(fname: "Bob", sname: "Newt", age: 42) // Java: c = new Customer(); c.setFname("Bob"); c.setSname("Newt"); c.setAge(42);
(Of course this starts to pay of if either you don’t want to create a constructor or if there are “many” properties and you need to set different subsets of them (constructor with 4+ arguments is hard to read).)
Reading a file:
assert test.method() == new File("expected.txt").getText() // Java: buffered reader line by line ...; Note: == actually uses equals()
Checking the content of a collection/map:
assert customerFinder.findAll().collect {it.sname}.sort() == ["Lizard","Newt"] // Java: too long to show here (extract only surnames, sort them, compare ...) assert getCapitalsMap() == ["UK" : "London", "CR" : "Prague"]
Regular expressions:
assert ("dog1-and-dog2" =~ /dog\d/).getAt([0,1]) == ["dog1", "dog2"]