Tuesday, May 26, 2009

New Power Assertions in Groovy

Over the holiday weekend Peter Niederwieser, author of Spock, quietly slipped improved assertion messages into Groovy 1.7, and announced it on the mailing list. The feature produces nicely formatted, text based error messages, which Spock has had since the initial release.

Here's an example of a simple boolean comparison failing:

def x = true
def y = false
assert x == y

Caught: Assertion failed:

assert x == y
| | |
| | false
| false
true

And here's what a failure looks like with lists:

def x = [1, 2, 3]
assert x == [3, 2, 1]

Caught: Assertion failed:

assert x == [3, 2, 1]
| |
| false
[1, 2, 3]

We could go on an on with the examples:

assert new File('foo.bar') == new File('example.txt')

Caught: Assertion failed:

assert new File('foo.bar') == new File('example.txt')
| | |
foo.bar | example.txt
false

Lastly, if you want to override the message printed on failure then you can still use the regular old exception syntax:

assert  true == false : 'true cannot be false'


The latest build is available through the Canoo build at http://build.canoo.com/groovy/artifacts/. Just click the latest build number and then click dist.

Thanks Peter!

No comments: