Testing Groovy with Spock

Site Admin · 11 Sep 2026 · 8 views

Introduction to Spock

Spock is the most popular testing framework for Groovy. It provides a clean, expressive syntax for writing unit and integration tests. Spock uses blocks like given, when, then, and expect to structure test cases clearly.

Your First Spock Test

class CalculatorSpec extends Specification {

    def "should add two numbers"() {
        given: "a calculator"
        def calc = new Calculator()

        when: "we add 2 and 3"
        def result = calc.add(2, 3)

        then: "the result is 5"
        result == 5
    }
}

Data-Driven Testing

Spock excels at parameterized tests using where: blocks:

def "should multiply correctly"() {
    expect:
    a * b == result

    where:
    a | b || result
    2 | 3 || 6
    0 | 5 || 0
    7 | 1 || 7
}

Mocking and Stubbing

Spock provides built-in mocking without external libraries:

class UserServiceSpec extends Specification {

    def userRepo = Mock(UserRepository)

    def "should find user by name"() {
        given:
        userRepo.findByName("Alice") >> new User(name: "Alice")

        when:
        def user = new UserService(userRepo).find("Alice")

        then:
        user.name == "Alice"
    }
}

Interaction Verification

Spock lets you verify that methods were called with specific arguments:

then:
1 * mockService.process(_)
0 * mockService.error(_)

Key Points

  • Spock uses given/when/then blocks for clear test structure.
  • Data-driven testing is built-in with where: blocks.
  • Spock includes mocking and stubbing without external dependencies.
  • Interaction verification confirms method calls on mocks.
  • Spock tests extend Specification and use descriptive string names.
Share this post:

Comments (0)

Please login or register to comment.