Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy 'assert': How to display the value?

Tags:

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?

like image 475
AppSensei Avatar asked Sep 28 '12 18:09

AppSensei


People also ask

How do I print a value in Groovy script?

You can print the current value of a variable with the println function.

How does assert work in Groovy?

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.

How do you use assert in if condition in Groovy?

The if's condition needs to be an expression. Assertions are for cases where you want it to fail loudly if what you're asserting is not true. Don't use assert unless you want it to throw an exception if the condition is not met.


2 Answers

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... } 
like image 65
user1708042 Avatar answered Oct 06 '22 00:10

user1708042


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

like image 22
Bill K Avatar answered Oct 05 '22 23:10

Bill K