Spring Boot Cucumber Component Test Example

Spring Boot Cucumber Component Test Example

This article walks through setting up Cucumber to perform component testing for a REST controller in Spring Boot.

In this guide, we’ll walk through how to create a component test for a Spring Boot @RestController using Cucumber. This approach will help us test the behavior of the /api/customers endpoint and ensure it behaves as expected.

🚀 Goal

The goal is to test that the /api/customers endpoint responds correctly with a 200 OK status. This verifies that our customer service API is working as intended.

🧱 Controller

Here’s the CustomerController class in Spring Boot, which exposes the /api/customers endpoint to get all customers.

@RestController
@RequestMapping("/api")
public class CustomerController {
    @GetMapping("/customers")
    public List<Map<String, String>> getAllCustomers() {
        return List.of(
            Map.of("id", "1", "name", "Alice"),
            Map.of("id", "2", "name", "Bob")
        );
    }
}

This controller is simple — it just returns a list of customers when the /customers endpoint is hit.


🧪 Dependencies (Maven)

To get Cucumber working with Spring Boot, we need to add a few dependencies to the pom.xml file. Here are the necessary dependencies that will allow us to use Cucumber for behavior-driven tests.

Add the following to your pom.xml:

<dependencies>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.12.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-spring</artifactId>
        <version>7.12.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>7.12.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

🧩 Cucumber Test Class

This is where we define the steps for our Cucumber test. These steps will interact with the CustomerController and verify that the API responds as expected.

package com.codingboot.componenttest;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class CustomerControllerSteps {

    private TestRestTemplate restTemplate = new TestRestTemplate();
    private ResponseEntity<String> response;

    @LocalServerPort
    private int port;

    @Given("the customer service is running")
    public void service_is_running() {
        // Spring Boot test context auto-starts
    }

    @When("I call the GET endpoint {string}")
    public void i_call_get_endpoint(String endpoint) {
        response = restTemplate.getForEntity("http://localhost:" + port + "/api/" + endpoint, String.class);
    }

    @Then("I should receive a 200 OK response")
    public void should_receive_200_response() {
        assertEquals(200, response.getStatusCodeValue());
    }
}

🧪 Cucumber Spring Context Class

This context class hooks Spring Boot and Cucumber together. It ensures the Spring Boot application runs in the background during tests.

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "com.codingboot.componenttest",
    plugin = {"pretty", "summary"}
)
@CucumberContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CucumberSpringContext {
    // Empty class just to hook Spring Boot and Cucumber
}

📁 Sample Feature File: src/test/resources/features/customer.feature

Here’s the Gherkin feature file, where we define the test scenario for the /customers endpoint.

Feature: Customer API

  Scenario: Get all customers
    Given the customer service is running
    When I call the GET endpoint "customers"
    Then I should receive a 200 OK response

✅ Test Output

Once you run the test, you should see output like this in your console:

Scenario: Get all customers                 # src/test/resources/features/customer.feature:3
  Given the customer service is running     # com.codingboot.componenttest.CustomerControllerSteps.service_is_running()
2025-05-03T14:26:22.642+05:30  INFO 40724 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2025-05-03T14:26:22.643+05:30  INFO 40724 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2025-05-03T14:26:22.644+05:30  INFO 40724 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
  When I call the GET endpoint "/customers" # com.codingboot.componenttest.CustomerControllerSteps.i_call_get_endpoint(java.lang.String)
  Then I should receive a 200 OK response   # com.codingboot.componenttest.CustomerControllerSteps.should_receive_200_response()

1 Scenarios (1 passed)
3 Steps (3 passed)
0m2.890s

This output confirms that the test passed successfully, showing that the /api/customers endpoint works as expected.


✅ Summary

This simple test verifies that the GET /api/customers endpoint is available and responds with a 200 OK status.