AppSensei
AppSensei

Reputation: 8400

Groovy 'assert': How to display the value?

How do I display a value whether it is true or false in groovy? I'm using Eclipse as my IDE.

    assert 4 * ( 2 + 3 ) - 6 == 14 //integers only

And also I don't understand 'assert' too well in Groovy. Is it like an if() statement/boolean in Java?

What role does 'assert' play in Groovy?

Upvotes: 34

Views: 91836

Answers (3)

user1708042
user1708042

Reputation: 1863

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...
}

Upvotes: 65

Bill K
Bill K

Reputation: 62769

Groovy asserts are now quite impressive! They will actually print out the value of every variable in the statement (which is fantastic for debugging)

for example, it might print something like this if b is 5, a is {it^2} and c is 15:

assert( a(b)  == c)
.       | |   |  |
.      25 |  !=  15
.         5

(Well--something like that--Groovy's would probably look a lot better).

If we could just get this kind of print-out on an exception line...

Upvotes: 14

Roberto Perez Alcolea
Roberto Perez Alcolea

Reputation: 1414

assert 'asserts' that the result of the expression will be a true

Upvotes: -3

Related Questions