Java Programming Tutorials

Java programming tutorials with many code examples!

Spock Framework before after test


How to run some initialization code before and/or after each test case/feature in Spock Framework? The following examples will clarify things out!


In JUnit you can run some code before and/or after test cases. The same can be done in Spock using setup() and cleanup() methods.

The following test makes it clear:

package com.farenda.solved

import spock.lang.Specification

class SetupCleanupTest extends Specification {

    // Will be initialized each time in setup()
    def List<String> cities

    def setup() {
        println('Setting up test data...')
        cities = ['Braavos', 'Volantis', 'Pentos']

    def cleanup() {
        println('Cleaning up after a test!')

    // Creating objects at the top level works like setup() method
    // and is performed before each test feature.
    // Here we create a closure and execute it immediately
    // to return a list and assign:
    def list = { println('setting up a list...'); return [1, 2, 3] }()

    def 'should remove Volantis'() {
        list == [1, 2 , 3]


        cities == ['Braavos', 'Pentos']

    def 'should add Meereen'() {
        cities << 'Meereen'

        cities == ['Braavos', 'Volantis', 'Pentos', 'Meereen']

Running the tests gives the following output:

$> gradle test --tests com.farenda.solved.SetupCleanupTest
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE

com.farenda.solved.SetupCleanupTest > should remove Volantis STANDARD_OUT
    setting up a list...
    Setting up test data...
    Cleaning up after a test!

com.farenda.solved.SetupCleanupTest > should add Meereen STANDARD_OUT
    setting up a list...
    Setting up test data...
    Cleaning up after a test!


Total time: 14.031 secs

As you can see setup() and cleanup() methods are called for each test feature. Global test variables are initialized before setup method – I put list initialization after setup() method on purpose, to show that order is irrelevant.

Was it helpful? Share!