31

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?

lospejos
  • 1,976
  • 3
  • 19
  • 35
AppSensei
  • 8,270
  • 22
  • 71
  • 99

3 Answers3

61

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...
}
user1708042
  • 1,740
  • 17
  • 20
13

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

Bill K
  • 62,186
  • 18
  • 105
  • 157
  • 2
    Being used to less capable assertions means you assume you need to do more work. Just write the complicated assert and watch the magic as everything gets printed out on failures. It truly is impressive – Bae Sep 05 '15 at 05:35
-1

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

Roberto Perez Alcolea
  • 1,408
  • 11
  • 11