Wednesday, November 09, 2011

A Failed assert Is Truly Groovy Baby

While I've been a fan of Groovy for some time, I wasn't a fan of assert in Groovy, it produced a big ugly stack trace and wasn't very readable. So I just ignored assert  as I have in Java.

Most developers ignore assert in Java, it was introduced late, it's complicated to work with from a tuning and performance perspective, we've been doing unit testing long before assert was introduced...

However the core Groovy community loves assert, almost all example code for Groovy,  beyond 'Hello World', uses assert to show what's going on. Example: Introduction to Groovy

So ignoring assert in Groovy, didn't feel very groovy; I was at odds with the community. Using assert didn't feel groovy either.

That changed last night as I debugging some code for the build system. I put in a quick assert as a sanity check and it failed, but it failed beautifully.  It produced one of the most beautiful error messages I've ever seen, it looked something like:

assert demo.calcA() == demo.calcB()
       |    |       |  |    |
       |    1       |  |    2
       |            |  AssertDemo@2c79809
       |            false

The perfect amount of information, quickly showing me what was happening in my code. Turns out Groovy 1.7 introduced Power Asserts because
Groovy's "assert" keyword has sometimes been criticized as it's, in a way, limited, as it just checks that the expression it's being passed is true or false. Unlike with testing frameworks such as JUnit/TestNG and the various additional assertion utilities, where you get nicer and more descriptive messages, Groovy's assert would just tell you the expression was false, and would give the value of variables used in the expression, but nothing more.
OK, so I'm not quite alone in my lack of love for the old assert.  The new Power Assert is a thing of beauty.

Power Assert was developed as part of Spock: a testing and specification framework for Java and Groovy applications.  I haven't used Spock, but it's now on the list of things to check out.

- Peace

No comments: