Grails Cookbook - A collection of tutorials and examples

Groovy Assert Examples

Assertions are important for checking some conditions are met. This post will show examples on how to perform assertion in Groovy language.

Positive Groovy Assert

To perform assert in Groovy is straightforward, below is a simple example:
def name = "John"
assert name == "John"
Since the condition results to true, the code will continue to execute and nothing is displayed in the console and no exceptions are thrown.

Negative Groovy Assert

if we change our assertion and did something that will evaluate to false, for example:

def name = "John"
assert name == "Peter"
An exception is raised, here is what's displayed on the screen:
Caught: Assertion failed: 
assert name == "Peter"
       |    |
       John false
Assertion failed: 
assert name == "Peter"
       |    |
       John false

Negative Groovy Assert with Message

We we assert in Groovy, we can introduce a message that will be displayed when an exception is thrown. We just need to use the colon symbol followed by the message. For example:
def name = "John"
assert name == "Peter" : "Name should be John"
When the expression evaluates to false, the message on the right side is displayed as part of the exception. Here is the output of the code above:
Caught: java.lang.AssertionError: Name should be John. Expression: (name == Peter). Values: name = John
java.lang.AssertionError: Name should be John. Expression: (name == Peter). Values: name = John

As shown in the output, the exception raised is of type java.lang.AssertionError. We can also catch it if we want to, for example:

try {
    def name = "John"
    assert name == "Peter" : "Name should be John"
} catch (AssertionError e) {
	println "Something bad happened: " + e.getMessage()
}
And the output of the code will be:
Something bad happened: Name should be John. Expression: (name == Peter). Values: name = John

Groovy Assert List Type

We can use assert on other data structure as well, it just needs to evaluate to a boolean. For example:

def list = [5, 10, 15, 20]
assert list == [5, 10, 15, 20]
This has no error because the two list are equal. If there is an error:
def list = [5, 10, 15, 20]
assert list == [35, 44, 67, 88]

This will produce an error, which is quite impressive:

Caught: Assertion failed: 
assert list == [35, 44, 67, 88]
       |    |
       |    false
       [5, 10, 15, 20]
Assertion failed: 
assert list == [35, 44, 67, 88]
       |    |
       |    false
       [5, 10, 15, 20]