Monday, August 17, 2009

Writing Unit-Tests for Java in Groovy: Not so brilliant after all?

Update 2009-08-18: I did only get halfway to true enlightenment... Dierk König was so kind to correct me in his comment (see comments bellow). Thanks!

1012471_bright_idea_4_colour_illustration.jpg There is advice out there, that it is a good idea to use Groovy for unit-testing your Java code. The following developerWorks article is a good example for this idea: Practically Groovy: Unit test your Java code faster with Groovy

There is even the opinion, that writing tests in Groovy can be a good starting point to secretly sneak Groovy into your Java project.

Dierk König was giving an interesting talk at gr8conf presenting "Seven Groovy usage patterns for Java developers".

Using Groovy for unit-testing would best fit the "House Elf"-pattern, along with using Groovy for build automation, deployment and functional tests.

But Dierk König did not mention unit-testing in his presentation!

When questioned about that, Dierk König gave an interesting answer:

Unit-Tests are ideally realized with Test Driven Development (TDD). But TDD is more about design than about testing, the resulting unit-tests are just a convenient by-product of the process.

So unit-tests should be a design tool, a mean to drive and evolve the underlying code.
Dierk König argued, that .. order to achieve the goals of TDD, unit-tests should be written in the same language as the underlying code.

Sounds pretty obvious to me...

It is clear that this is only valid for true unit-tests. Integration-tests and functional-tests are a completely different story. I think thats the area where more expressive languages like Groovy can shine.

Thats probably also a reason why the real BDD scene seems to prefer Ruby and Groovy...


  1. Well, you are misquoting me a little ;-)

    I did not say that the unit tests should be written in the same language as the implementation language but in the same language as the expected user of your API. A subtle but important distinction.

    For example in the Groovy project we implement lots of logic in Java but test them from Groovy because that is the intended use of that API.

    In other places we test Groovy code from Java to see how the usage works and feels like from that perspective.

  2. @Dierk

    Thanks for your correction!
    I updated the post, mentioning your comment.

  3. I agree to a point. TDD is about making good API decisions by consuming the API before writing the implementation. Using Groovy to test Java will cause you to ignore issues with checked exceptions in your system under test and also will push you towards a List and Map heavy API. But if you keep this in mind when writing the tests then you can certainly use Groovy to test Java. There are many other benefits of Groovy and you have to weigh the benefit against the cost of a slightly less beneficial TDD flow.


Related Posts Plugin for WordPress, Blogger...