ZetCode

Groovy assert

last modified June 26, 2026

The assert keyword checks that a condition is true and throws a PowerAssertionError with a detailed diagnostic when it is not. Groovy's power assert is far more informative than Java's standard assert, making it a popular tool for tests, scripts, and defensive programming.

Basic Definition

assert evaluates a boolean expression. When the expression is true, execution continues silently. When it is false, Groovy throws a PowerAssertionError that includes a visual breakdown of every sub-expression involved.

Unlike Java's assert, which is disabled by default and requires the -ea JVM flag, Groovy's assert is always enabled and is designed to be used freely in production scripts and unit tests.

Simple assert

The basic form is assert expression. A passing assertion produces no output; a failing one prints the power assert diagram.

SimpleAssert.groovy
def x = 10

assert x == 10   // passes silently
assert x > 5     // passes silently
assert x < 20    // passes silently

println "All assertions passed"

All three conditions are true, so the script completes and prints the final message. No output is produced for passing assertions.

$ groovy SimpleAssert.groovy
All assertions passed

Failing Assertion — Power Assert Output

When an assertion fails, Groovy prints a visual diagram showing the value of every sub-expression in the condition.

FailingAssert.groovy
def a = 3
def b = 7

assert a + b == 15

The sum is 10, not 15, so the assertion fails. The power assert output maps each operand and intermediate result back to its position in the expression.

$ groovy FailingAssert.groovy
Exception in thread "main" org.codehaus.groovy.runtime.powerassert.PowerAssertionError:
assert a + b == 15
       | | |
       3 10 7

Assert with a Message

A custom message can be attached to an assert using a colon. The message is displayed together with the power assert diagram when the assertion fails.

AssertMessage.groovy
def age = 15

assert age >= 18 : "User must be at least 18, got $age"

The string after the colon is evaluated only when the assertion fails. It can be any Groovy expression, including GString interpolation.

$ groovy AssertMessage.groovy
Exception in thread "main" org.codehaus.groovy.runtime.powerassert.PowerAssertionError:
assert age >= 18 : User must be at least 18, got 15
       |
       15

Asserting String Values

assert works with any expression that produces a boolean, including string comparisons and method calls.

AssertStrings.groovy
def greeting = "Hello, Groovy"

assert greeting.startsWith("Hello")
assert greeting.contains("Groovy")
assert greeting.size() == 13
assert greeting.toUpperCase() == "HELLO, GROOVY"

println "String assertions passed"

Each method call returns a boolean that assert evaluates. A failing call would show the actual string value and the result of the method in the power assert output.

$ groovy AssertStrings.groovy
String assertions passed

Asserting Collections

Assertions on collections verify size, membership, and ordering.

AssertCollections.groovy
def numbers = [2, 4, 6, 8, 10]

assert numbers.size() == 5
assert numbers.contains(6)
assert !numbers.contains(7)
assert numbers.every { it % 2 == 0 }
assert numbers.sum() == 30
assert numbers.first() == 2
assert numbers.last() == 10

every returns true only if all elements satisfy the closure. When any of these assertions fails, the power assert diagram shows the collection contents and the failing sub-expression side by side.

$ groovy AssertCollections.groovy

Asserting Maps

assert can validate map contents, key presence, and value equality.

AssertMaps.groovy
def user = [name: "Alice", age: 30, active: true]

assert user.name == "Alice"
assert user.age >= 18
assert user.active
assert user.containsKey("name")
assert !user.containsKey("email")
assert user.size() == 3

println "Map assertions passed"

A truthy check like assert user.active is equivalent to assert user.active == true. Groovy evaluates the value directly using its truthy rules.

$ groovy AssertMaps.groovy
Map assertions passed

Asserting Null and Non-null

assert is commonly used to verify that a value is or is not null.

AssertNull.groovy
def result = "data"
def missing = null

assert result != null : "result must not be null"
assert result          // truthy assert - fails for null or empty

assert missing == null : "missing should be null"
assert !missing        // truthy assert - passes for null

println "Null assertions passed"

A bare assert value passes for any truthy value and fails for null, empty strings, empty collections, and zero. Use assert value != null when you need to distinguish null from other falsy values.

$ groovy AssertNull.groovy
Null assertions passed

Asserting Numeric Ranges

The Groovy in operator checks range membership and works well inside assert.

AssertRange.groovy
def temperature = 22
def score = 85

assert temperature in 15..30 : "Temperature $temperature out of expected range"
assert score in 0..100       : "Score $score is invalid"

def grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"
assert grade == "B"

println "Range assertions passed"

in with a range calls Range.contains, which checks both bounds inclusively. This is more readable than writing two separate comparison operators.

$ groovy AssertRange.groovy
Range assertions passed

Asserting Custom Objects

assert evaluates any expression, including properties and methods of custom classes.

AssertCustom.groovy
class Rectangle {
    int width
    int height

    int area()      { width * height }
    int perimeter() { 2 * (width + height) }
    boolean isSquare() { width == height }
}

def rect = new Rectangle(width: 4, height: 6)

assert rect.area() == 24
assert rect.perimeter() == 20
assert !rect.isSquare()

def square = new Rectangle(width: 5, height: 5)
assert square.isSquare()
assert square.area() == 25

println "Custom object assertions passed"

When an assertion on a custom object fails, the power assert diagram prints the object's toString representation alongside the failing sub-expression, helping diagnose unexpected state.

$ groovy AssertCustom.groovy
Custom object assertions passed

Chained Expression Assertions

Power assert is most useful with complex chained expressions because it shows every intermediate value on failure.

ChainedAssert.groovy
def words = ["Groovy", "is", "awesome"]

assert words.collect { it.toLowerCase() }.join(" ") == "groovy is awesome"
assert words.findAll { it.length() > 2 }.size() == 2
assert words.any { it.startsWith("G") }
assert words.max { it.length() } == "awesome"

If any of these assertions failed, the power assert output would display the list contents, the result of each intermediate closure, and the final value, pointing precisely to what went wrong.

$ groovy ChainedAssert.groovy

assert in Methods

assert is commonly placed at the start of a method to validate preconditions and at the end to verify postconditions.

AssertPrecondition.groovy
double divide(double a, double b) {
    assert b != 0 : "Divisor must not be zero"
    def result = a / b
    assert result.isFinite() : "Result must be finite"
    result
}

println divide(10, 4)
println divide(7, 2)

Precondition asserts guard against invalid inputs. Postcondition asserts verify that the computed result meets expectations. Both approaches aid debugging without the overhead of full exception handling.

$ groovy AssertPrecondition.groovy
2.5
3.5

assert vs Java assert

Groovy's assert differs from Java's assert in two important ways: it is always enabled and it produces the power assert diagnostic output.

AssertVsJava.groovy
// Groovy assert - always active, power assert output
def val = 5
assert val == 5   // always runs

// Java's assert is DISABLED by default; to enable it you need:
// java -ea MyClass
// Groovy ignores the -ea flag - all asserts are always on

println "Groovy assert is always enabled"

Because Groovy assert is always active, it is suitable for unit tests and defensive scripting. In performance-critical inner loops, consider replacing assert with an explicit if check if the overhead is a concern.

$ groovy AssertVsJava.groovy
Groovy assert is always enabled

Source

Groovy Power Asserts Documentation

This tutorial covered the Groovy assert keyword, power assert diagnostic output, assertion messages, and asserting strings, collections, maps, ranges, and custom objects.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Groovy tutorials.