Java Reference
In-Depth Information
These tests use the
when
/
then
blocks, which are used as a stimulus/response pair. Any
code can be added to the
when
block, but the
then
block must consist of Boolean ex-
pressions, as with
expect
. The expressions are evaluated automatically, using the Groovy
Truth. This means that non-null references, non-empty strings, and non-zero numbers all
evaluate to true.
The
charAt
methodin
String
throwsanexceptionifitsargumentisnegativeorbeyond
the end of the string. The previous two tests show both conditions, using the
thrown()
and
notThrown()
methods. The
thrown
method can return the exception if you want
to process it further, using one of two variations in syntax
Exception e = thrown()
or
e = thrown(Exception)
where the
Exception
can be any specific exception class.
Consider the following test, which also introduces the extremely useful
old
method.
Listing 6.27. Another spec, illustrating the
old
method
class
QuoteSpec
extends
Specification {
String quote = """I am endeavoring, ma'am, to construct a
mnemonic memory circuit, using stone knives and bear skins."""
List<String> strings
def
setup() { strings = quote.
tokenize
(" ,.") }
def
"test string has 16 words"() {
expect: strings.size() == 16
}
def
"adding a word increases total by 1"() {
when: strings << 'Fascinating'
then: strings.size() == old(strings.size()) + 1
}
}