The power assert

assert is a statement with a condition. When the condition is true nothing happens; when it is false the program stops with a message that shows the value of every part of the expression. That diagram is the "power assert", and it is why a Groovy test often needs no assertion library.

A failing assertion

The script below catches the error and prints its message, so the diagram appears without the launcher's preamble. The values in it are the real ones:

power.groovy

def a = 5 def b = 7 try { assert a * b == 30 } catch (AssertionError error) { println error.message }

groovy power.groovy

assert a * b == 30
       | | | |
       5 | 7 false
         35

Each column under the expression is one value: 5 for a, 7 for b, 35 for the product, and false for the comparison. A wrong expectation is visible without a debugger, which is the point.

An assertion nobody catches

Left uncaught, the same error ends the script with a stack trace and exit status 1. The launcher prints the message twice: once with Caught: and once as the exception it rethrows.

uncaught.groovy

def items = ['a', 'b'] assert items.size() == 3 : 'the list must hold three items'

groovy uncaught.groovy

Caught: java.lang.AssertionError: the list must hold three items. Expression: (items.size() == 3)
java.lang.AssertionError: the list must hold three items. Expression: (items.size() == 3)
at uncaught.run(uncaught.groovy:3)
exit status: 1

The message after the colon replaces the diagram when the condition is false, and appears after it when there is no colon. Both forms stop the program: an assertion is not a warning.

Assertions in a test

Groovy assertions are on by default, also in a class compiled with groovyc; the JVM flag -ea belongs to Java's own assert keyword. A Spock specification uses expect: and then:, which are assertions with the same idea and a better report, as the Spock lesson shows.

Related

Автор статьи: Arthur Isaev