Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Testing with Spock

Your First Spock Specification

Learn Spock, the Groovy testing framework: Specification classes, given-when-then blocks, expect, thrown(), setup and cleanup, @Shared and readable failure output.

Spock is the testing framework most Groovy and many Java teams choose. A test is called a specification, its methods are features with names written as plain sentences, and every feature is divided into labelled blocks that read like a story: given this, when that happens, then expect this. Spock also produces unusually clear failure messages, because it understands the code of your assertions.

Spock and Groovy cannot run on this site, so Spock code is read-only. The Java stand-ins below imitate the given-when-then flow with a tiny hand-made test runner, so you can practice the structure.

A first specification

GROOVY
import spock.lang.Specification

class StackSpec extends Specification {

  def "a new stack is empty"() {
    given: "an empty stack"
    def stack = new ArrayDeque<Integer>()

    expect: "it has no elements"
    stack.isEmpty()
    stack.size() == 0
  }

  def "push adds an element on top"() {
    given:
    def stack = new ArrayDeque<Integer>()

    when:
    stack.push(42)

    then:
    stack.size() == 1
    stack.peek() == 42
  }
}

Points to notice:

  • The class extends spock.lang.Specification and is usually named ...Spec.
  • A feature method is an ordinary method whose name is a string: def "push adds an element on top"(). Test reports show it exactly like that.
  • Inside then: and expect: every line is an implicit assertion. You write stack.size() == 1, and no assert keyword.
  • A feature needs at least one block with assertions, and the blocks follow a fixed order.

The blocks

Block Purpose
given: (or setup:) Create the objects and state
when: The action under test (one stimulus)
then: Outcomes: assertions, exception checks, interactions
expect: Condition and stimulus in one block, for simple pure functions
cleanup: Release resources, runs even if the feature fails
where: Data for data-driven tests
and: Splits any block into labelled parts

The pair when: + then: describes "do something, check the result". Use expect: when there is nothing to "do", such as Math.max(1, 2) == 2.

GROOVY
def "max returns the larger number"() {
  expect:
  Math.max(a, b) == c
  // (a, b, c come from a where: block, see the next lesson)
}

Testing exceptions

GROOVY
def "popping an empty stack fails"() {
  given:
  def stack = new ArrayDeque<Integer>()

  when:
  stack.pop()

  then:
  thrown(NoSuchElementException)
}

thrown(Type) passes if the when: block throws that type (or a subclass). Capture it to inspect details: def e = thrown(IllegalArgumentException) followed by e.message == "bad". The opposite, notThrown(Type), and noExceptionThrown() check that nothing happened.

Shared setup: fields and setup()

Each feature runs on a fresh instance of the specification class. State is never shared between features, so tests cannot affect one another.

GROOVY
class CartSpec extends Specification {
  Cart cart                       // re-created for each feature

  @Shared
  def expensiveResource = connectToDb()     // created once for the whole spec

  def setup() {                   // runs before every feature
    cart = new Cart()
  }

  def cleanup() {                 // runs after every feature
    cart = null
  }

  def setupSpec() { }             // once, before the first feature
  def cleanupSpec() { }           // once, after the last feature
}

@Shared fields are the only instance state that survives between features. Keep them rare, because they couple tests.

Failure output that explains itself

When an assertion fails, Spock prints each sub-expression with its value:

TEXT
Condition not satisfied:

stack.size() == 2
|     |      |
|     1      false
[42]

You see the object, the value of size() and the comparison. This replaces the guess-what-was-null game of many Java assertions. Add and: blocks and descriptions to make features self-documenting.

Other useful annotations

  • @Unroll is the default behavior for where: features in modern Spock, so you rarely need it.
  • @Ignore("reason") skips a feature; @IgnoreIf({ os.windows }) and @Requires skip conditionally.
  • @Timeout(5) fails a feature that runs longer than five seconds.
  • @Stepwise runs features in order, sharing state. Use sparingly.
  • @Title("...") and @Narrative("...") document the specification.

Running specifications

Spock runs on the JUnit Platform, so Gradle's test task, Maven Surefire, and IDEs run it like any other test. A typical Gradle setup is shown in Gradle build scripts: add the org.spockframework:spock-core dependency and useJUnitPlatform().

Try it: given-when-then in Java (stand-in)

A tiny runner executes named "features" and prints a pass or fail line, mirroring how Spock reports sentence-named tests.

Java Stand-in: sentence-named features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: a fresh instance per feature (stand-in)

Spock creates a new specification object for each feature. This program shows why that isolates state compared with a shared field.

Java Stand-in: isolation between features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do lines inside a then: block act as?

    Every top-level boolean expression in then: and expect: is checked automatically, so no assert keyword is needed.
  2. 2. How do you check that a when: block throws IllegalStateException?

    thrown(Type) in the then: block verifies the exception.
  3. 3. How is state shared between features of one specification?

    Each feature gets a fresh specification instance; only @Shared fields live across features.
  4. 4. When should you use expect: instead of when: + then:?

    expect: combines the stimulus and the condition in one block for simple cases.

Summary

  • A Spock test is a Specification class whose features have sentence names.
  • Blocks given, when, then, expect, cleanup and where structure each feature.
  • Conditions in then: and expect: are implicit assertions with detailed failure output.
  • thrown(Type) checks exceptions.
  • Each feature runs on a fresh instance; @Shared is the exception.

Next: Data-Driven Testing with where: