Chapter 2. Specification Basics
Spock is a straightforward and expressive language for writing automated tests for software. It is based on the Groovy programming language but can be used to test code written in any language that runs on the Java Virtual Machine (JVM)—Java, Scala, Kotlin, even JavaScript. In this first chapter, we look at how to create specifications in Spock; how individual tests, or feature methods, are structured; how to make assertions; and how the lifecycle of a specification works.
If you’ve used JUnit or another unit testing framework before, some of the ideas might seem familiar. However, don’t worry if you haven’t. Although Spock is built on top of JUnit’s test runner, that’s really just to make the Spock specifications easy to run anywhere JUnit tests can run. The syntax used to express test code in Spock is pretty different.
Anatomy of a Specification
Spock test classes—known as specifications—are written in Groovy.
Here is a simple Spock specification:
import
spock.lang.*
class
IntegerSpec
extends
Specification
{
def
"an integer can be incremented"
()
{
given:
int
i
=
1
when:
i
++
then:
i
==
2
}
}
This is an extremely straightforward test that just ensures the integer increment operator ++
works as expected.
If you know Java, there are probably some familiar things (the import
statement, class and variable declarations, increment operator, and Boolean expression) and some less familiar things (the def
keyword; weird-looking method names, given:
, when: ...
Get Spock: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.