You are here
Home > java >

Spock Framework with Spring Boot: Practical Java Testing Guide

Spock Framework with Spring Boot: A Practical Guide to Clearer Java Tests

Spock Framework with Spring Boot practical Java testing guide featuring Groovy code, Java 25, Spring Boot 4.0.9, Spock 2.5 and Groovy 6.0.0.Testing is an important part of developing reliable Spring Boot applications. As applications grow, testing business logic, repository interactions, REST APIs, and exception-handling scenarios becomes increasingly important.

Most Java developers are already familiar with JUnit and Mockito. These tools are widely used for writing unit tests and mocking dependencies. However, there is another testing framework that offers a different approach to writing tests: Spock Framework.

Spock is a testing and specification framework built on Groovy. It provides a readable syntax for describing application behavior, built-in mocking capabilities, interaction verification, and data-driven testing.

One interesting thing about Spock is that you do not need to rewrite your existing Java application in Groovy. You can continue writing your production code in Java and use Groovy only for test cases.

In this tutorial, we will integrate Spock Framework with Spring Boot and build a practical Product Inventory REST API. We will write unit tests for business logic, test repository interactions, verify REST endpoints, handle exceptions, and explore parameterized testing.

By the end of this tutorial, you will understand how Spock works and how to use it in your existing Java and Spring Boot projects.

Table of Contents

What You Will Learn

After completing this tutorial, you will be able to:

  • Understand the basic concepts of Spock Framework.
  • Integrate Spock with an existing Spring Boot application.
  • Configure Maven dependencies for Groovy and Spock.
  • Write readable unit tests using Given-When-Then blocks.
  • Create mocks, stubs, and interaction-based tests.
  • Test Spring Boot REST controllers.
  • Write data-driven tests using the ‘where:’ block.
  • Test exception handling and business validation.
  • Understand the differences between Spock and JUnit with Mockito.

Prerequisites

Before proceeding, you should have basic knowledge of:

  • Core Java and object-oriented programming.
  • Spring Boot fundamentals.
  • REST API development.
  • Maven dependency management.
  • Basic unit testing concepts.

You do not need previous experience with Groovy. We will introduce the Groovy syntax whenever it is required.

What Is Spock Framework?

Spock is an open-source testing and specification framework for Java and Groovy applications.

Unlike traditional Java testing frameworks, Spock uses Groovy to define test cases. Groovy is a JVM-based programming language that has a concise and expressive syntax. The main objective of Spock is to make tests easier to read, understand, and maintain.

Consider a simple requirement:

“When a customer requests a product that exists in the inventory, the application should return the product details.”

A traditional JUnit test can verify this requirement, but Spock allows us to express the scenario in a more descriptive format.

For example:

def "should return product when product exists"() {
    given:
    def product = new Product(
        1L, "Keyboard", 3499.00, 10
    )

    when:
    def result = productService.getProduct(1L)

    then:
    result.name() == "Keyboard"
    result.availableQuantity() == 10
}

The test method name itself describes the expected behavior.

Spock provides several useful features:

Feature Description
BDD-style syntax Organizes tests into readable blocks
Built-in mocking Creates mocks without requiring Mockito for basic use
Interaction testing Verifies method calls and their arguments
Data-driven testing Tests multiple inputs using one specification
Expressive assertions Provides detailed failure information
Spring integration Supports Spring-based testing through spock-spring

Another advantage is that Spock tests run on the JUnit Platform. This makes it possible to use Spock alongside other compatible testing engines in the same project.

Spock is not limited to testing Groovy applications. It can test ordinary Java classes, Spring services, repositories, and REST controllers.

Why Use Spock Instead of JUnit and Mockito?

JUnit and Mockito are excellent testing tools. They are widely adopted and remain a strong choice for Java projects.

However, Spock offers some additional conveniences.

More readable test cases

In Spock, a test is called a feature method.

A feature method can contain descriptive blocks such as:

  • given: – Prepare the test data and required objects.
  • when: – Execute the operation being tested.
  • then: – Verify the expected result.
  • expect: – Perform an operation and directly verify its result.
  • where: – Supply multiple test inputs.
  • cleanup: – Release resources after execution.

This structure makes the purpose of each section clear.

Built-in mocking

With JUnit, developers commonly use Mockito to create mock objects.

For example:

@Mock private ProductRepository productRepository;

With Spock, we can create the same type of mock directly:

ProductRepository productRepository = Mock()

You can also define expected method calls and return values in the test itself.

Data-driven testing

Suppose a method accepts a discount percentage. You want to test several possible values.

Instead of writing separate test methods, Spock allows you to provide multiple inputs using a ‘where:’ block.

This makes parameterized testing easier to maintain.

Interaction verification

Sometimes checking the returned result is not enough.

For example, when reserving inventory, you may also want to verify that the repository’s save() method was called exactly once.

Spock provides a simple syntax for verifying such interactions.

Better test readability

Spock tests can look closer to business requirements than conventional test methods.

This is particularly useful when developers need to understand what an application is expected to do without reading a large amount of implementation code.

Setting Up Spock in a Spring Boot Project: Spock Framework with Spring Boot

Now let’s create a Spring Boot application and integrate Spock into it.

Technology Stack

We will use the following technologies:

Technology Version
Java 25
Spring Boot 4.0.9
Spock Framework 2.5
Groovy 6.0.0
Maven 3.9+
Spring Boot Test Managed by Spring Boot
IDE STS

The production application will use Java. Groovy will be used only for writing test specifications.

What application will we build?

We will develop a small Product Inventory REST API.

The application will support the following operations:

HTTP Method Endpoint Purpose
GET /api/products/{id} Retrieve product details
POST /api/products/{id}/reserve Reserve product quantity

Our application will follow a simple layered architecture.

             HTTP Request
                  |
                  v
          ProductController
                  |
                  v
            ProductService
                  |
                  v
          ProductRepository
                  |
                  v
             Data Store

We will focus on testing the service and controller layers.

Create the Spring Boot project

Create a Spring Boot project using Spring Initializr.

Select:

  • Project: Maven
  • Language: Java
  • Spring Boot: 4.0.9
  • Java: 25
  • Dependencies: Spring Web

We will add the testing dependencies manually.

Project structure

Organize the application as follows:

spring-boot-spock-demo/
|
├── pom.xml
|
└── src/
    |
    ├── main/
    │   └── java/
    │       └── com/example/catalog/
    │           |
    │           ├── CatalogApplication.java
    │           |
    │           ├── controller/
    │           │   └── ProductController.java
    │           |
    │           ├── service/
    │           │   └── ProductService.java
    │           |
    │           ├── repository/
    │           │   ├── ProductRepository.java
    │           │   └── InMemoryProductRepository.java
    │           |
    │           ├── model/
    │           │   ├── Product.java
    │           │   └── ReserveRequest.java
    │           |
    │           └── exception/
    │               ├── ProductNotFoundException.java
    │               ├── InsufficientStockException.java
    │               └── GlobalExceptionHandler.java
    |
    └── test/
        └── groovy/
            └── com/example/catalog/
                |
                ├── service/
                │   └── ProductServiceSpec.groovy
                |
                └── controller/
                    └── ProductControllerSpec.groovy

We use the Spec suffix for Spock test classes. This makes it easy to distinguish them from regular Java test classes.

Configure Maven dependencies

Open pom.xml and add the following configuration.

First, define the Spring Boot parent and version properties:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.0.9</version>
    <relativePath/>
</parent>

<properties>
    <java.version>25</java.version>
    <groovy.version>6.0.0</groovy.version>
    <spock.version>2.5-groovy-6.0</spock.version>
</properties>

Now add the dependencies:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Testing -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- Groovy -->
    <dependency>
        <groupId>org.apache.groovy</groupId>
        <artifactId>groovy</artifactId>
        <version>${groovy.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spock Core -->
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-core</artifactId>
        <version>${spock.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spock Spring Integration -->
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-spring</artifactId>
        <version>${spock.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Why do we need these dependencies?

  • spring-boot-starter-test provides Spring testing utilities, MockMvc, and other test support.
  • groovy provides the Groovy language runtime.
  • spock-core provides the core Spock testing framework.
  • spock-spring integrates Spock with Spring’s testing infrastructure.

Notice that we have selected the 2.5-groovy-6.0 Spock artifact. The Groovy version in the dependency configuration should match the selected Spock variant.

Configure Maven to compile Groovy tests

Maven does not compile Groovy test files automatically just because the Groovy dependency is present.

We need the GMavenPlus plugin.

Add the following configuration inside the build section:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>4.2.1</version>

            <executions>
                <execution>
                    <goals>
                        <goal>addTestSources</goal>
                        <goal>compileTests</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>

            <configuration>
                <includes>
                    <include>**/*Spec.class</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>

The GMavenPlus plugin adds Groovy test sources and compiles them.

The Surefire configuration tells Maven to discover test classes ending with Spec.

Spock 2.x uses the JUnit Platform, so its engine can execute the compiled specifications through the normal Maven test lifecycle.

After completing the configuration, execute:

mvn clean test

Maven should download the required dependencies and compile the project.

At this point, we are ready to implement our application.

Writing Your First Spock Unit Test

Let’s start by implementing the Product model and service layer.

Create the Product model

Create Product.java.

package com.example.catalog.model;

import java.math.BigDecimal;

public record Product(
        Long id,
        String name,
        BigDecimal price,
        int availableQuantity
) {
}

We are using a Java record to represent an immutable product object.

Create the ProductRepository interface

package com.example.catalog.repository;

import com.example.catalog.model.Product;
import java.util.Optional;

public interface ProductRepository {

    Optional<Product> findById(Long id);

    Product save(Product product);
}

This interface defines the operations required by our service.

Implement an in-memory repository

For this tutorial, we will use a simple in-memory implementation instead of introducing a database.

Create InMemoryProductRepository.java.

package com.example.catalog.repository;

import com.example.catalog.model.Product;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class InMemoryProductRepository
        implements ProductRepository {

    private final Map<Long, Product> products =
            new ConcurrentHashMap<>();

    public InMemoryProductRepository() {
        products.put(
            1L,
            new Product(
                1L,
                "Mechanical Keyboard",
                new BigDecimal("3499.00"),
                12
            )
        );
    }

    @Override
    public Optional<Product> findById(Long id) {
        return Optional.ofNullable(products.get(id));
    }

    @Override
    public Product save(Product product) {
        products.put(product.id(), product);
        return product;
    }
}

The repository contains one sample product.

We are using ConcurrentHashMap for basic thread-safe access to the in-memory data structure. This is a demonstration implementation, not a replacement for a persistent database.

Create custom exceptions

We need two exceptions for our business scenarios.

ProductNotFoundException.java:

package com.example.catalog.exception;

public class ProductNotFoundException
        extends RuntimeException {

    public ProductNotFoundException(Long id) {
        super("Product not found with ID: " + id);
    }
}

InsufficientStockException.java:

package com.example.catalog.exception;

public class InsufficientStockException
        extends RuntimeException {

    public InsufficientStockException(String message) {
        super(message);
    }
}

Implement the ProductService

Create ProductService.java.

package com.example.catalog.service;

import com.example.catalog.exception.*;
import com.example.catalog.model.Product;
import com.example.catalog.repository.ProductRepository;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    private final ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Product getProduct(Long id) {

        return productRepository.findById(id)
                .orElseThrow(
                    () -> new ProductNotFoundException(id)
                );
    }

    public Product reserveStock(Long id, int quantity) {

        if (quantity <= 0) {
            throw new IllegalArgumentException(
                "Quantity must be greater than zero"
            );
        }

        Product product = getProduct(id);

        if (product.availableQuantity() < quantity) {
            throw new InsufficientStockException(
                "Insufficient stock for product: " + product.name()
            );
        }

        Product updatedProduct = new Product(
                product.id(),
                product.name(),
                product.price(),
                product.availableQuantity() - quantity
        );

        return productRepository.save(updatedProduct);
    }
}

There are two important business operations here.

  1. getProduct() retrieves a product and throws an exception when it does not exist.
  2. reserveStock() validates the requested quantity, checks available inventory, and saves the updated product.

We will use these operations to understand different Spock testing features.

Write the first Spock specification

Create ProductServiceSpec.groovy inside the service test package.

package com.example.catalog.service

import com.example.catalog.model.Product
import com.example.catalog.repository.ProductRepository
import spock.lang.Specification

import java.math.BigDecimal
import java.util.Optional

class ProductServiceSpec extends Specification {

    ProductRepository productRepository = Mock()

    ProductService productService =
            new ProductService(productRepository)

    def "should return product when product exists"() {

        given:
        def product = new Product(
                1L,
                "Mechanical Keyboard",
                new BigDecimal("3499.00"),
                12
        )

        when:
        def result = productService.getProduct(1L)

        then:
        1 * productRepository.findById(1L) >>
                Optional.of(product)

        result.id() == 1L
        result.name() == "Mechanical Keyboard"
        result.availableQuantity() == 12
    }
}

Let’s understand what is happening.

First, we create a mock of ProductRepository.

ProductRepository productRepository = Mock()

This means we do not need a real repository or database for this unit test.

Second, we inject the mock into ProductService.

ProductService productService =
        new ProductService(productRepository)

Third, we execute the service method.

def result = productService.getProduct(1L)

Finally, we define the expected repository interaction.

1 * productRepository.findById(1L) >>
        Optional.of(product)

This statement means:

  • The repository method must be called exactly once.
  • It must be called with ID 1L.
  • It must return the supplied product.

The remaining statements verify the returned object.

This is our first practical example of Spock’s interaction-based testing.

Mocking Services and Repositories

Mocking is one of the most useful features of Spock.

It allows us to test one component without depending on the actual implementation of another component.

Let’s explore this with our Product Inventory application.

What is a mock?

A mock is a test object that allows us to define expected method calls and responses.

For example:

ProductRepository repository = Mock()

We can define the expected response:

repository.findById(1L) >>
        Optional.of(product)

When the service calls findById(1L), the mock returns the product without accessing the real repository.

Testing repository interaction

Let’s verify that the repository’s save() method is called when a customer reserves stock.

Add the following test to ProductServiceSpec.groovy.

def "should reduce available stock after reservation"() {

    given:
    def product = new Product(
            1L,
            "Mechanical Keyboard",
            new BigDecimal("3499.00"),
            12
    )

    when:
    def result = productService.reserveStock(1L, 4)

    then:
    1 * productRepository.findById(1L) >>
            Optional.of(product)

    1 * productRepository.save({
        it.availableQuantity() == 8
    }) >> { savedProduct -> savedProduct }

    result.availableQuantity() == 8
}

Here, we are testing more than the returned result.

We are verifying that the repository saves a product with eight available units.

The initial quantity is 12, and the customer reserves four units.

Therefore:

Available Stock = 12
Reserved Stock  = 4
Remaining Stock = 8

The expression inside save() checks the actual argument passed to the repository.

This is particularly useful when testing services that perform calculations or modify application state.

Understanding Mock, Stub, and Spy

Spock supports three commonly used types of test doubles.

Type Purpose
Mock Verifies interactions between objects
Stub Provides predefined responses
Spy Wraps a real object and allows selected behavior to be controlled

Mock example:

ProductRepository repository = Mock()

Stub example:

ProductRepository repository = Stub()

repository.findById(1L) >>
        Optional.of(product)

A stub is useful when you only need to provide a response and do not need to verify method-call counts.

Spy example:

ProductService service = Spy(
        new ProductService(productRepository)
)

A spy wraps a real object. You can use it when you want to observe or override selected behavior while retaining the original implementation for other methods.

In normal unit testing, prefer mocks or stubs when they make the test simpler. Use spies only when there is a clear reason.

Writing Spring Boot Integration Tests

Until now, we have tested the service independently.

However, real Spring Boot applications contain several components working together.

We also need to verify that Spring can initialize the application context and inject the required dependencies.

This is where Spring integration testing becomes useful.

Spock provides Spring integration through the spock-spring module.

The important annotations include:

  • @SpringBootTest
  • @SpringBean
  • @SpringSpy
  • @Autowired

Understanding @SpringBootTest

The @SpringBootTest annotation loads the Spring application context for testing.

For example:

import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Specification

@SpringBootTest
class ApplicationIntegrationSpec extends Specification {

    def "application context should load successfully"() {

        expect:
        true
    }
}

This simple test verifies that the Spring application context can be initialized.

Unlike a service unit test, this test uses Spring’s dependency injection and application configuration.

By default, @SpringBootTest does not start a real HTTP server. We can use its web environment options when a real server is required.

For controller testing, we will use MockMvc instead.

Understanding @SpringBean

Spock provides @SpringBean to register a mock or stub in the Spring application context.

Consider:

@SpringBean
ProductService productService = Mock()

This tells Spock to provide a mock ProductService for the Spring test context.

The controller can then receive this mock through its normal dependency injection.

This is useful because we can test the controller without depending on the actual service implementation.

Controller Testing with Spock

Now let’s expose our service through REST endpoints.

Create the request model

Create ReserveRequest.java.

package com.example.catalog.model; 

public record ReserveRequest(int quantity) {
}

This class represents the JSON request body for reserving stock.

Implement ProductController

Create ProductController.java.

package com.example.catalog.controller;

import com.example.catalog.model.*;
import com.example.catalog.service.ProductService;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping("/{id}")
    public Product getProduct(@PathVariable Long id) {

        return productService.getProduct(id);
    }

    @PostMapping("/{id}/reserve")
    public Product reserveStock(
            @PathVariable Long id,
            @RequestBody ReserveRequest request) {

        return productService.reserveStock(
                id,
                request.quantity()
        );
    }
}

We have exposed two REST endpoints.

The first endpoint retrieves product details.

The second endpoint reserves the requested quantity.

Implement global exception handling

Create GlobalExceptionHandler.java.

package com.example.catalog.exception;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ProductNotFoundException.class)
    public ResponseEntity<String> handleNotFound(
            ProductNotFoundException ex) {

        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(ex.getMessage());
    }

    @ExceptionHandler(InsufficientStockException.class)
    public ResponseEntity<String> handleInsufficientStock(
            InsufficientStockException ex) {

        return ResponseEntity
                .status(HttpStatus.CONFLICT)
                .body(ex.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleBadRequest(
            IllegalArgumentException ex) {

        return ResponseEntity
                .badRequest()
                .body(ex.getMessage());
    }
}

This allows us to return meaningful HTTP status codes when something goes wrong.

For example:

Scenario HTTP Status
Product exists 200 OK
Product not found 404 Not Found
Insufficient inventory 409 Conflict
Invalid quantity 400 Bad Request

Write ProductControllerSpec

Now let’s test the REST controller.

Create ProductControllerSpec.groovy inside the controller test package.

package com.example.catalog.controller

import com.example.catalog.model.Product
import com.example.catalog.service.ProductService

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.http.MediaType
import org.springframework.test.context.bean.override.mockito.MockitoBean
import org.spockframework.spring.SpringBean
import org.springframework.test.web.servlet.MockMvc

import spock.lang.Specification

import java.math.BigDecimal

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*

@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerSpec extends Specification {

    @Autowired
    MockMvc mockMvc

    @SpringBean
    ProductService productService

    def "should return product details through REST API"() {

        given:
        def product = new Product(
                1L,
                "Mechanical Keyboard",
                new BigDecimal("3499.00"),
                12
        )

        productService.getProduct(1L) >> product

        expect:
        mockMvc.perform(get("/api/products/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.name")
                        .value("Mechanical Keyboard"))
                .andExpect(jsonPath("$.availableQuantity")
                        .value(12))
    }

    def "should reserve product stock through REST API"() {

        given:
        def updatedProduct = new Product(
                1L,
                "Mechanical Keyboard",
                new BigDecimal("3499.00"),
                8
        )

        productService.reserveStock(1L, 4) >>
                updatedProduct

        when:
        def response = mockMvc.perform(
                post("/api/products/1/reserve")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content('{"quantity":4}')
        )

        then:
        response.andExpect(status().isOk())
                .andExpect(jsonPath("$.availableQuantity")
                        .value(8))
    }
}

Note: This example uses Spring Framework’s @SpringBean annotation to replace the service bean in the test context. It uses Spock for the test structure and execution, while Mockito supplies the Spring-managed mock.

This is an important distinction: Spock provides its own @SpringBean integration, so you do not need Mockito when you choose to use Spock mocks throughout the test.

What are we verifying?

In the first test, we verify that:

  • The controller receives the HTTP GET request.
  • The service returns the expected product.
  • The API returns HTTP 200.
  • The JSON response contains the correct product details.

In the second test, we verify that:

  • The controller receives a POST request.
  • The request body contains the requested quantity.
  • The service returns the updated product.
  • The API returns the updated inventory quantity.

We are testing the web layer with Spring MVC and MockMvc without starting an actual HTTP server.

Data-Driven Testing Using where:

One of Spock’s most useful features is data-driven testing.

Suppose we want to validate that a reservation quantity must always be greater than zero.

We could write separate test methods for zero and negative values.

However, Spock provides a better approach.

The “‘where:”‘ block allows us to execute the same feature method with different input values.

Testing invalid quantities

Add the following test to ProductServiceSpec.groovy.

def "should reject invalid reservation quantities"() {

    when:
    productService.reserveStock(1L, quantity)

    then:
    thrown(IllegalArgumentException)

    where:
    quantity << [0, -1, -5]
}

Let’s understand this example.

The where: block supplies three different values:

where:
quantity << [0, -1, -5]

Spock executes the feature method once for each value.

Therefore, this single test method represents three test iterations.

Each iteration verifies that an invalid quantity causes an IllegalArgumentException.

Using data tables

Spock also supports data tables.

For example, suppose we want to test the remaining inventory after different reservations.

def "should calculate remaining stock correctly"() {

    given:
    def product = new Product(
            1L,
            "Keyboard",
            new BigDecimal("3499.00"),
            12
    )

    when:
    def result = productService.reserveStock(
            1L,
            reservedQuantity
    )

    then:
    1 * productRepository.findById(1L) >>
            Optional.of(product)

    1 * productRepository.save({
        it.availableQuantity() == expectedStock
    }) >> { saved -> saved }

    result.availableQuantity() == expectedStock

    where:
    reservedQuantity | expectedStock
    2                | 10
    4                | 8
    6                | 6
    10               | 2
}

The first column represents the requested quantity.

The second column represents the expected remaining inventory.

This approach is especially useful when testing calculations, validation rules, business conditions, and different input combinations.

Exception Handling and Interaction Testing

Testing successful scenarios is important, but a reliable application must also handle failure scenarios correctly.

Let’s test two important cases in our Product Inventory application.

Testing product not found

When a product does not exist, our service should throw ProductNotFoundException.

Add this test to ProductServiceSpec.groovy.

def "should throw exception when product does not exist"() {

    when:
    productService.getProduct(99L)

    then:
    1 * productRepository.findById(99L) >>
            Optional.empty()

    thrown(ProductNotFoundException)
}

Here, we configure the repository mock to return an empty Optional.

The service should then throw the expected exception.

Testing insufficient inventory

Suppose a product has only five available units, but a customer tries to reserve eight units.

The application should reject the request.

def "should reject reservation when stock is insufficient"() {

    given:
    def product = new Product(
            1L,
            "Keyboard",
            new BigDecimal("3499.00"),
            5
    )

    when:
    productService.reserveStock(1L, 8)

    then:
    1 * productRepository.findById(1L) >>
            Optional.of(product)

    0 * productRepository.save(_)

    thrown(InsufficientStockException)
}

Notice this statement:

0 * productRepository.save(_)

It verifies that the repository’s save() method must not be called.

The underscore _ is a wildcard argument matcher in Spock.

This is an important testing scenario because we are not only verifying that an exception occurs. We are also verifying that no inventory update is performed after an unsuccessful reservation.

Testing the controller’s exception response

We can also verify the HTTP status returned when a product does not exist.

Add the following feature method to ProductControllerSpec.groovy.

def "should return 404 when product is missing"() {

    given:
    productService.getProduct(99L) >>
            { throw new ProductNotFoundException(99L) }

    expect:
    mockMvc.perform(get("/api/products/99"))
            .andExpect(status().isNotFound())
}

This verifies that the global exception handler converts the service exception into an HTTP 404 response.

Similarly, we can test the insufficient-stock scenario and expect HTTP 409.

These tests help ensure that our REST API behaves consistently in both successful and unsuccessful situations.

Spock vs JUnit 5 and Mockito

Now that we have implemented several tests using Spock, let’s compare it with the traditional JUnit and Mockito combination.

Comparison JUnit 5 + Mockito Spock
Programming language Java Groovy
Test structure Annotations and methods Specification blocks
Mock creation Mockito Built-in
Stubbing Mockito syntax >> operator
Interaction verification verify() Interaction expressions
Parameterized tests @ParameterizedTest where:
Spring Boot integration Supported Supported
Assertion style JUnit assertions Groovy conditions

For example, Mockito interaction verification typically looks like this:

verify(productRepository, times(1))
        .findById(1L);

The equivalent Spock interaction looks like this:

1 * productRepository.findById(1L)

Both approaches verify the expected interaction.

However, Spock provides a more compact syntax.

Should you replace JUnit with Spock?

Not necessarily.

JUnit is widely adopted and integrates with a large Java testing ecosystem.

Spock is a useful alternative when you want:

  • More expressive test specifications.
  • Built-in mocking and interaction testing.
  • Convenient data-driven tests.
  • A BDD-oriented testing style.
  • Less repetitive test code in suitable scenarios.

You can also introduce Spock gradually into an existing Java project without rewriting production classes.

Common Mistakes and Troubleshooting

While integrating Spock into a Spring Boot project, developers may encounter a few common problems.

Let’s discuss some of them.

Groovy test files are not getting compiled

Problem: Maven executes the Java tests but ignores Groovy specifications.

Reason: The project does not have the correct Groovy test compilation configuration.

Solution: Add GMavenPlus with the addTestSources and compileTests goals.

Also ensure that your specifications are stored under:

src/test/groovy/

Spock tests are not discovered by Maven

Problem: The Groovy test classes compile successfully, but Maven does not execute them.

Reason: The test naming pattern may not match the Surefire configuration.

Solution: Ensure your classes end with Spec and configure Surefire accordingly.

<includes> 
   <include>**/*Spec.class</include> 
</includes>

Also verify that the Spock engine is present on the test classpath.

Groovy and Spock version mismatch

Problem: Compilation or runtime errors occur after adding dependencies.

Reason: The selected Spock artifact may target a different Groovy version.

Solution: Keep the versions aligned.

For this tutorial:

<groovy.version>6.0.0</groovy.version>
<spock.version>2.5-groovy-6.0</spock.version>

Avoid mixing a Groovy 6 runtime with a Spock artifact intended for a different Groovy generation.

Spring beans are not injected

Problem: A controller or service dependency is null or the Spring context fails to start.

Reason: The application may not be using the correct Spring test annotation or mock integration.

Solution: For Spring-managed tests, use the appropriate integration:

@SpringBootTest
class ProductControllerSpec extends Specification { 
   // Test implementation 
}

For a Spock-managed Spring mock:

@SpringBean
ProductService productService = Mock()

Make sure spock-spring is included in the test dependencies.

Tests are dependent on each other

Problem: A test passes individually but fails when the complete test suite runs.

Reason: Shared mutable state or test data may be affecting multiple tests.

Solution: Keep test data isolated. Prefer fresh objects and avoid unnecessary shared fields.

Spock provides fixture methods such as setup(), cleanup(), setupSpec(), and cleanupSpec() when additional lifecycle management is needed.

Best Practices for Writing Spock Tests

Here are some recommendations that can help you write maintainable Spock specifications.

1. Use descriptive feature names

Prefer:

def "should reject reservation when stock is insufficient"()

Instead of:

def "testReservation"()

The first name explains the expected behavior.

2. Keep each test focused

A test should ideally verify one behavior or closely related set of conditions.

Avoid combining unrelated business scenarios into one large feature method.

3. Use mocks only when required

Do not mock every object unnecessarily.

Use real objects for simple data models and utility classes. Mock external dependencies such as repositories, remote clients, or message publishers when appropriate.

4. Prefer data-driven tests for repetitive scenarios

If the same business rule needs to be checked against several input values, use ‘where:’ rather than creating multiple nearly identical methods.

5. Verify important interactions

When a business operation should save data, publish an event, or call another component, verify the expected interaction.

However, avoid verifying every internal method call. Tests should focus on meaningful application behavior rather than implementation details.

6. Separate unit tests and integration tests

Use ordinary Spock specifications for service unit tests.

Use Spring integration annotations when you actually need the Spring container, dependency injection, MVC infrastructure, or application configuration.

7. Keep production code in Java if that is your project standard

There is no requirement to migrate the entire application to Groovy.

You can use Spock exclusively for tests while keeping the production code in Java.

FAQs (Frequently Asked Questions)

Q1. Can we use Spock with Spring Boot?

Yes. Spock can be integrated with Spring Boot through the spock-spring module.

Spring Boot’s official documentation describes support for Spock 2.2 or later with the Groovy 4 variant in the Spring Boot 3.5 generation.

Q2. Do we need to write production code in Groovy to use Spock?

No. You can write your complete production application in Java.

Groovy is required for the Spock specifications, not for your business classes.

Q3. Is Spock better than JUnit 5?

Neither framework is universally better.

JUnit 5 is a natural choice for Java-focused projects and has a broad ecosystem.

Spock offers a more expressive syntax, built-in mocking, and convenient data-driven testing.

The choice depends on team experience, project requirements, and maintainability.

Q4. Does Spock require Mockito?

No. Spock provides its own mocking, stubbing, and spying capabilities.

However, it can also work with Mockito when there is a specific requirement to use Mockito-based mocks.

Q5. Can we use Spock for REST API testing?

Yes. You can use Spock with Spring’s MockMvc to test REST controllers, request handling, HTTP responses, and exception handling.

Q6. Does Spock support parameterized testing?

Yes. Spock provides data-driven testing through ‘where:’ blocks.

You can supply multiple values using data tables, collections, and other data providers.

Q7. Can Spock and JUnit coexist in the same Spring Boot project?

Yes. Spock 2.x uses the JUnit Platform, so it can run alongside other compatible testing engines.

This allows teams to adopt Spock gradually without immediately migrating existing JUnit tests.

Q8. Is Spock suitable for microservices testing?

Yes. Spock can test service-layer logic, REST controllers, Spring application contexts, and interactions with external dependencies.

For larger integration scenarios, you can combine it with tools such as Testcontainers and WireMock.

Conclusion

Spock Framework provides an alternative way to write automated tests for Java and Spring Boot applications.

Its Groovy-based syntax makes test cases expressive and easy to understand. Features such as Given-When-Then blocks, built-in mocking, interaction verification, and data-driven testing can help reduce repetitive testing code.

In this tutorial, we integrated Spock with Spring Boot and implemented a Product Inventory REST API. We explored service unit testing, repository mocking, Spring integration testing, controller testing, parameterized tests, and exception handling.

One of the biggest advantages of Spock is that you can introduce it into an existing Java application without changing your production code.

If your team is comfortable with Java but wants to explore a more expressive testing approach, Spock is definitely worth evaluating.

You do not have to replace JUnit and Mockito immediately. Start with a small service or module, write a few Spock specifications, and compare the readability and maintainability of both approaches.

That is a practical way to decide whether Spock deserves a place in your Spring Boot testing strategy.


Official Documentation and References

  1. Spock Framework 2.5 Reference Documentation
  2. Spock Framework Release Notes
  3. Spring Boot 3.5 Testing Documentation
  4. Spring Boot 3.5 System Requirements
  5. GMavenPlus Plugin Documentation

 

Leave a Reply



Top