π₯ Bridging Business Scenarios and Enterprise API Verification
In modern agile enterprise software delivery, ensuring that software engineers, quality architects, and product managers share a precise, unambiguous mental model of API contracts is critical. Cucumber BDD (Behavior-Driven Development) bridges this communication divide by expressing system integrations, business rules, and validation acceptance criteria in plain, human-readable Gherkin language (Given, When, Then, And). Rather than locking assertions inside black-box test scripts, Cucumber binds ubiquitous business phrasing to low-level HTTP automation using RestAssured. By implementing PicoContainer Dependency Injection to share session state across step classes without static singletons, mapping complex nested JSON payloads with Cucumber DataTables, and orchestrating multi-threaded execution via TestNG parallel runners, engineering teams build maintainable, living test specifications.
CUCUMBER BDD API AUTOMATION PIPELINE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. SPECIFICATION LAYER: Feature Files (*.feature) β
β Feature: Student Enrollment Lifecycle β
β Scenario: Register candidate with valid qualifications β
β Given an authenticated administrator session β
β When the admin registers a candidate with course "API-PRO-101" β
β Then the response status code should be 201 β
β And the generated student ID matches pattern "STU-[0-9]{5}" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Cucumber Expression Engine)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2. GLUE / BINDING LAYER: Step Definitions (*StepDefinitions.java) β
β @Given("an authenticated administrator session") β
β @When("the admin registers a candidate with course {string}") β
β @Then("the response status code should be {int}") β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Injects Shared State per Scenario)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 3. DEPENDENCY INJECTION CONTAINER: PicoContainer (cucumber-picocontainer) β
β - Instantiates a fresh TestContext for EVERY scenario automatically β
β - Shares RequestSpecification, Response, and Dynamic Entities across distinct step classes β
β - Prevents static variable cross-thread contamination during concurrent execution β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 4. EXECUTION & ASSERTION ENGINE: RestAssured, Jackson & Hamcrest β
β - Translates parameters into HTTP headers, query params, and JSON POJO payloads β
β - Transmits over wire socket -> Receives response -> Evaluates Hamcrest assertions β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Background, executing end-to-end user journeys, and leveraging Scenario Outline with parameter matrices.
@api @regression
Feature: Student Enrollment & Academic Lifecycle API Management
As an administrator of the Nikita Infotech Portal
I want to register, query, and update student enrollments via REST API
So that academic records and course allocations are strictly maintained
Background:
Given the student management service is operational
And an authorized administrator Bearer token is attached to the request
@smoke @crud
Scenario: Successfully register a new student and retrieve their record
When an administrator submits a registration payload with:
| fullName | email | courseCode | age | credits |
| Nikita Sharma | nikita.sharma@nikita-infotech.com| API-PRO-101 | 24 | 4 |
Then the response status code should be 201
And the response header "Content-Type" should contain "application/json"
And the response body should contain a valid student identifier
When the administrator retrieves the student by their generated ID
Then the response status code should be 200
And the retrieved student full name should be "Nikita Sharma"
And the student academic status should be "ACTIVE"
@boundary @validation
Scenario Outline: Validate enrollment business rule boundaries for course <courseCode>
When an administrator submits a registration with age <age> and course "<courseCode>"
Then the response status code should be <expectedStatus>
And the error code should be "<expectedErrorCode>"
Examples:
| courseCode | age | expectedStatus | expectedErrorCode |
| API-PRO-101 | 17 | 422 | ERR_UNDERAGE_STUDENT |
| API-PRO-101 | 18 | 201 | NONE |
| API-PRO-101 | 65 | 201 | NONE |
| API-PRO-101 | 66 | 422 | ERR_OVERAGE_STUDENT |
| UNKNOWN-999 | 25 | 404 | ERR_COURSE_NOT_FOUND |
cucumber-picocontainer. A centralized TestContext object stores mutable request specifications, responses, and created entity IDs across different step definition classes.
package com.nikitainfotech.api.context;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import java.util.HashMap;
import java.util.Map;
public class TestContext {
private RequestSpecification requestSpec;
private Response response;
private String generatedStudentId;
private final Map<String, Object> sessionData = new HashMap<>();
public TestContext() {
// Automatically instantiates a fresh context per Cucumber Scenario
this.requestSpec = new RequestSpecBuilder()
.setBaseUri("https://api.nikita-infotech.com")
.setBasePath("/v1")
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.build();
}
public RequestSpecification getRequestSpec() { return requestSpec; }
public void setRequestSpec(RequestSpecification spec) { this.requestSpec = spec; }
public Response getResponse() { return response; }
public void setResponse(Response response) { this.response = response; }
public String getGeneratedStudentId() { return generatedStudentId; }
public void setGeneratedStudentId(String studentId) { this.generatedStudentId = studentId; }
public void setSessionVariable(String key, Object value) { sessionData.put(key, value); }
public Object getSessionVariable(String key) { return sessionData.get(key); }
}
StudentStepDefinitions.java. PicoContainer injects the shared TestContext directly into the constructor.
package com.nikitainfotech.api.steps;
import com.nikitainfotech.api.context.TestContext;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
public class StudentStepDefinitions {
private final TestContext context;
// PicoContainer automatically injects the active Scenario TestContext here
public StudentStepDefinitions(TestContext context) {
this.context = context;
}
@Given("the student management service is operational")
public void verifyServiceOperational() {
given()
.spec(context.getRequestSpec())
.when()
.get("/health")
.then()
.statusCode(200);
}
@Given("an authorized administrator Bearer token is attached to the request")
public void attachAdminBearerToken() {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.active_mock_token_2026";
context.setRequestSpec(
given().spec(context.getRequestSpec()).header("Authorization", "Bearer " + token)
);
}
@When("the administrator retrieves the student by their generated ID")
public void retrieveStudentByGeneratedId() {
String studentId = context.getGeneratedStudentId();
Response res = given()
.spec(context.getRequestSpec())
.when()
.get("/students/" + studentId);
context.setResponse(res);
}
@When("an administrator submits a registration with age {int} and course {string}")
public void registerStudentWithAgeAndCourse(int age, String courseCode) {
Map<String, Object> payload = new HashMap<>();
payload.put("fullName", "Boundary Candidate");
payload.put("email", "boundary." + System.currentTimeMillis() + "@nikita-infotech.com");
payload.put("courseCode", courseCode);
payload.put("age", age);
payload.put("credits", 4);
Response res = given()
.spec(context.getRequestSpec())
.body(payload)
.when()
.post("/students");
context.setResponse(res);
}
}
@DataTableType in a TypeRegistryConfigurer to transform Gherkin DataTables directly into strongly typed Java domain objects using Jackson.
package com.nikitainfotech.api.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nikitainfotech.api.models.StudentRegistrationModel;
import io.cucumber.java.DataTableType;
import java.util.Map;
public class DataTableTransformer {
private final ObjectMapper objectMapper = new ObjectMapper();
// Automatically converts a single-row DataTable map into our Java POJO
@DataTableType
public StudentRegistrationModel defineStudent(Map<String, String> entry) {
return new StudentRegistrationModel(
entry.get("fullName"),
entry.get("email"),
entry.get("courseCode"),
Integer.parseInt(entry.get("age")),
Integer.parseInt(entry.get("credits"))
);
}
}
// Consuming the strongly-typed POJO in Step Definitions:
package com.nikitainfotech.api.steps;
import com.nikitainfotech.api.context.TestContext;
import com.nikitainfotech.api.models.StudentRegistrationModel;
import io.cucumber.java.en.When;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
public class StudentRegistrationSteps {
private final TestContext context;
public StudentRegistrationSteps(TestContext context) {
this.context = context;
}
@When("an administrator submits a registration payload with:")
public void submitRegistrationDataTable(StudentRegistrationModel studentPayload) {
// Cucumber automatically converts the Gherkin DataTable into our POJO!
Response res = given()
.spec(context.getRequestSpec())
.body(studentPayload)
.when()
.post("/students");
context.setResponse(res);
if (res.getStatusCode() == 201) {
String createdId = res.jsonPath().getString("id");
context.setGeneratedStudentId(createdId);
}
}
}
CommonAssertionStepDefinitions.java to provide universal assertion steps for status codes, headers, response times, and RFC error envelopes across all feature files.
package com.nikitainfotech.api.steps;
import com.nikitainfotech.api.context.TestContext;
import io.cucumber.java.en.Then;
import io.restassured.response.Response;
import org.testng.Assert;
import static org.hamcrest.Matchers.*;
public class CommonAssertionStepDefinitions {
private final TestContext context;
public CommonAssertionStepDefinitions(TestContext context) {
this.context = context;
}
@Then("the response status code should be {int}")
public void assertStatusCode(int expectedStatusCode) {
Response response = context.getResponse();
Assert.assertNotNull(response, "Response object is null! Did you execute an HTTP request?");
response.then().statusCode(expectedStatusCode);
}
@Then("the response header {string} should contain {string}")
public void assertResponseHeader(String headerName, String expectedHeaderValue) {
context.getResponse().then().header(headerName, containsString(expectedHeaderValue));
}
@Then("the response body should contain a valid student identifier")
public void assertValidStudentId() {
context.getResponse().then().body("id", matchesPattern("^STU-[0-9]{5}$"));
}
@Then("the retrieved student full name should be {string}")
public void assertRetrievedFullName(String expectedName) {
context.getResponse().then().body("fullName", equalTo(expectedName));
}
@Then("the student academic status should be {string}")
public void assertAcademicStatus(String expectedStatus) {
context.getResponse().then().body("status", equalTo(expectedStatus));
}
@Then("the error code should be {string}")
public void assertErrorCode(String expectedErrorCode) {
if (!"NONE".equalsIgnoreCase(expectedErrorCode)) {
context.getResponse().then().body("errorCode", equalTo(expectedErrorCode));
}
}
}
@Before and @After hooks to delete created entities and attach failure diagnostics.
package com.nikitainfotech.api.hooks;
import com.nikitainfotech.api.context.TestContext;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import static io.restassured.RestAssured.given;
public class ScenarioHooks {
private final TestContext context;
public ScenarioHooks(TestContext context) {
this.context = context;
}
@Before(order = 1)
public void logScenarioStart(Scenario scenario) {
System.out.println("================================================================================");
System.out.println("STARTING SCENARIO: " + scenario.getName());
System.out.println("Tags: " + scenario.getSourceTagNames());
System.out.println("Thread ID: " + Thread.currentThread().getId());
System.out.println("================================================================================");
}
@After(order = 10)
public void purgeCreatedEntityOnTeardown(Scenario scenario) {
String studentId = context.getGeneratedStudentId();
// If an entity was provisioned during the test, purge it from the database
if (studentId != null && !studentId.trim().isEmpty()) {
System.out.println("[TEARDOWN] Purging created student: " + studentId);
given()
.spec(context.getRequestSpec())
.when()
.delete("/students/" + studentId)
.then()
.statusCode(anyOf(is(200), is(204), is(404)));
}
}
@After(order = 20)
public void attachDiagnosticsOnFailure(Scenario scenario) {
if (scenario.isFailed() && context.getResponse() != null) {
String responseDetails = "Failed Status: " + context.getResponse().getStatusCode() + "\n"
+ "Response Body:\n" + context.getResponse().asPrettyString();
// Attach raw response details directly to Cucumber HTML Report
scenario.attach(responseDetails.getBytes(), "text/plain", "HTTP Response Failure Trace");
}
}
}
TestNgTestRunner.java by subclassing AbstractTestNGCucumberTests and overriding scenarios() with parallel = true for multi-threaded test execution.
package com.nikitainfotech.api.runners;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
import org.testng.annotations.DataProvider;
@CucumberOptions(
features = "src/test/resources/features",
glue = {
"com.nikitainfotech.api.steps",
"com.nikitainfotech.api.hooks",
"com.nikitainfotech.api.config"
},
plugin = {
"pretty",
"html:target/cucumber-reports/cucumber.html",
"json:target/cucumber-reports/cucumber.json",
"io.qameta.allure.cucumber7jvm.AllureCucumber7Jvm"
},
tags = "@api and not @ignore",
monochrome = true
)
public class TestNgTestRunner extends AbstractTestNGCucumberTests {
// Override scenarios data provider to enable multi-threaded execution
@Override
@DataProvider(parallel = true)
public Object[][] scenarios() {
return super.scenarios();
}
}
pom.xml with cucumber-java, cucumber-picocontainer, cucumber-testng, and allure-cucumber7-jvm for automated pipeline execution.
<!-- MAVEN POM DEPENDENCIES FOR CUCUMBER RESTASSURED ARCHITECTURE -->
<dependencies>
<!-- Cucumber Core & Java Engine -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.15.0</version>
<scope>test</scope>
</dependency>
<!-- Cucumber PicoContainer for Dependency Injection -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>7.15.0</version>
<scope>test</scope>
</dependency>
<!-- Cucumber TestNG Integration -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.15.0</version>
<scope>test</scope>
</dependency>
<!-- Allure Reporting for Cucumber 7 -->
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-cucumber7-jvm</artifactId>
<version>2.25.0</version>
<scope>test</scope>
</dependency>
</dependencies>
CUCUMBER BDD API AUTOMATION REFERENCE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ
β KEYWORD / DIRECTIVE β SYNTAX EXAMPLE β PRIMARY PURPOSE & BEHAVIOR β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Feature: β Feature: Student API β Declares the high-level business domain scope β
β Background: β Background: Given auth token β Runs shared prerequisite steps before each test β
β Scenario Outline: β Scenario Outline: Test age β Parameterizes scenarios across multiple test rowsβ
β Examples: β Examples: | val1 | val2 | β Tabular data matrix feeding Scenario Outline β
β DataTable β | key | val | in step body β Passes structured key-value maps or lists to stepβ
β @DataTableType β @DataTableType POJO map(..) β Converts Gherkin tables directly to Java POJOs β
β PicoContainer β Constructor(TestContext ctx) β Injects scenario-scoped state across step classesβ
β @Before / @After β @After public void clean(..) β Manages setup fixtures and teardown data removal β
β @CucumberOptions β features="..", glue=".." β Points runner to feature files and step packages β
β parallel = true β @DataProvider(parallel=true) β Runs scenarios concurrently across worker threadsβ
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 CUCUMBER BDD API BEST PRACTICES: β
β 1. Write user-centric steps: Avoid exposing low-level HTTP details like POST /api/v1/resource in Gherkin. β
β 2. Use PicoContainer for state: Never share data between step classes using static variables. β
β 3. Transform tables to POJOs: Use @DataTableType to map data tables cleanly into domain models. β
β 4. Clean up in @After hooks: Purge provisioned test entities after each scenario to keep databases clean β
β 5. Tag scenarios strategically: Use @smoke, @regression, and @api tags to filter CI test execution. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ