Groovy ‘assert’: How to display the value?

An assertion is similar to an if, it verifies the expression you provide: if the expression is true it continues the execution to the next statement (and prints nothing), if the expression is false, it raises an AssertionError.

You can customize the error message providing a message separated by a colon like this:

assert 4 * ( 2 + 3 ) - 5 == 14 : "test failed"

which will print:

java.lang.AssertionError: test failed. Expression: (((4 * (2 + 3)) - 5) == 14)

but I had to change the values of your test, in order to make it fail.

The use of assertions is up to your taste: you can use them to assert something that must be true before going on in your work (see design by contract).

E.g. a function that needs a postive number to work with, could test the fact the argument is positive doing an assertion as first statement:

def someFunction(n) {
    assert n > 0 : "someFunction() wants a positive number you provided $n"
    ...
    ...function logic...
}

Leave a Comment