Groovy 1.7 Power Assert

Posted on December 11, 2009. Filed under: Groovy | Tags: |

I already mentioned this in my previous post, but I wanted to go a little bit deeper on this: the new Groovy Power Assert (and no, let’s not call is GPA).

Groovy Power Assert makes assertions quite more powerful. The best way to demonstrate is ofcourse by example. When running the following code in Groovy 1.6:

a = 10
b = 9

assert 91 == a * b

This will be your output:

Exception thrown: Expression: (92 == (a * b)). Values: a = 10, b = 9

java.lang.AssertionError: Expression: (92 == (a * b)). Values: a = 10, b = 9

While quite helpful, Groovy 1.7 introduced an even better assert, which was initially developed for the Spock framework. The new output of running the above in a Groovy 1.7 console is this:

Exception thrown

Assertion failed: 

assert 91 == a * b
          |  | | |
          |  10| 9
          |    90


Which gives you much more insight in why the assert fails. You don’t have to use numbers, you can use any type of object to assert on, and the assert statement will call the toString method of that class, as demonstrated below:

def names = [ 'erik', 'marcel', 'sebastien' ]
def reverse = names.reverse()

assert ['sebastien', 'erik', 'marcel'] == reverse

Which will output the following:

assert ['sebastien', 'erik', 'marcel'] == reverse
                                       |  |
                                       |  [sebastien, marcel, erik]

Quite funky he? Groovy now gives you some nicely formatted assert information which will help you to tackle your failed tests even faster!

PS: (okay, okay, I added this later….) The same works for special Groovy objects, like GPathResults. For example, check the following code:

def xml = new XmlParser().parseText("<test>x</test>")
assert "y" == xml.text()

The result of this:

assert "y" == xml.text()
           |  |   |
           |  |   x
           |  test[attributes={}; value=[x]]

(Mykola, is this what you meant?)

Read Full Post | Make a Comment ( 6 so far )

Liked it here?
Why not try sites on the blogroll...