CodeToLive

Testing with Spock Framework

Spock is a testing and specification framework for Java and Groovy applications that combines the best features of JUnit, Mockito, and other testing tools.

Why Spock?

  • Highly expressive specification language
  • Built-in mocking and stubbing
  • Parameterized testing
  • Clear, readable test reports
  • Integrates with JUnit runners

Basic Spock Test

import spock.lang.Specification

class MathSpec extends Specification {
    def "maximum of two numbers"() {
        expect:
        Math.max(a, b) == c
        
        where:
        a | b | c
        1 | 2 | 2
        5 | 3 | 5
        0 | 0 | 0
    }
}

Test Structure

Spock tests are structured in blocks:

def "should add two numbers correctly"() {
    given: "two numbers"
    def a = 5
    def b = 3
    
    when: "they are added"
    def result = a + b
    
    then: "the result should be correct"
    result == 8
}

Common Blocks

Block Purpose
given/setup Setup test conditions
when Perform the action
then Assert the results
expect Combine when+then
cleanup Clean resources
where Data-driven testing

Mocking with Spock

def "should send notification when order is placed"() {
    given: "a notification service and order processor"
    def notificationService = Mock(NotificationService)
    def orderProcessor = new OrderProcessor(notificationService)
    
    when: "an order is placed"
    orderProcessor.process(new Order())
    
    then: "a notification should be sent"
    1 * notificationService.send(_)
}

Advanced Features

  • Interaction testing: Verify method calls
  • Stubbing: Define method return values
  • Exception testing: Verify exceptions
  • Shared objects: Reuse between tests
  • Extensions: Custom test behavior

Integrating with Grails

Grails has built-in support for Spock:

# Create a Spock test in Grails
grails create-unit-test com.example.BookService
← Back to Tutorials