Java Reference
In-Depth Information
def "LLaP has 21 characters"() {
expect: llap. size () == 21
}
def "LLaP has 4 words"() {
expect: llap.split(/ \W/ ).size() == 4
}
def "LLaP has 6 vowels"() {
expect: llap. findAll (/ [aeiou] /).size() == 6
}
}
Theclassextends spock.lang.Specification ,whichiswhatmakesitaSpocktest.
The spec is testing a String , so it has an attribute named llap . In the setup method,
the llap variable is assigned to the string “Live Long and Prosper.” The setup method
runs before each test, similar to @Before in JUnit 4. JUnit 3 contains a method called
setUp that does the same thing, but in Spock the setup method is written in lowercase,
with a def keyword.
The test methods, known as feature methods in the Spock documentation, are written in
block structure. In each of the test methods shown here, there's a single block called ex-
pect . The expect block consists of a series of Boolean expressions, each of which must
evaluate to true for the test to pass.
The three sample tests check (1) the number of characters in the test string; (2) that there
are four words in the test string, based on splitting the string at non-word boundaries; and
(3) that the test string has a total of six vowels, again based on a regular expression.
Like JUnit 4, Spock tests can verify that exceptions are thrown. Spock tests can also verify
that exceptions are not thrown. Consider the following two tests, which are added to the
previous listing:
def "Access inside the string doesn't throw an exception"() {
when: s.charAt(s.size() - 1)
then: notThrown(IndexOutOfBoundsException)
}
def "Access beyond the end of the string throws exception"() {
when: s.charAt(s.size() + 1)
then: thrown(IndexOutOfBoundsException)
}
Search WWH ::




Custom Search