QA and Test Automation ยท Lab 21 of 35
Cucumber BDD on a Checkout: Java and Python, Step by Step
Write Gherkin for ShopRung's coupon and shipping rules and automate it: Cucumber JVM with JUnit 5 in Java, or behave in Python. Feature files, step definitions, shared scenario state, scenario outlines, data tables, tags and reports. 9 scenarios.
โฑ 75 minIntermediate๐ธ Free8 stepsJava + Python
Java 21 + MavenCucumber 7.20 + JUnit 5.11Jackson 2.18Python 3.12 + behave 1.3 + httpx (second path)ShopRung
Overview video
What you will build
A BDD suite for ShopRung's checkout rules, written so a product owner can read it and a machine can run it:
coupons.feature: SAVE10 at exactly $50.00 (total $49.99), a Scenario Outline for SAVE10 at 3, 4 and 5 notebooks, the expired WELCOME15 and an unknown code.shipping.feature: a data table cart one cent below $75.00 (shipping $4.99, total $79.98) and the free shipping boundary at exactly $75.00.- Thin step definitions that call a small ShopRung API client, with state shared per scenario (PicoContainer in Java, behave's
contextin Python). - Tags (
@smoke), an HTML report (Java) or JUnit XML (Python), and three ShopRung bugs that each fail exactly the scenario that describes them.
Before you start
- The episodes behind it: BDD and Gherkin and Cucumber with Java.
- Java 21 and Maven from your first Java test project, or Python 3.12 from the pytest API lab.
- ShopRung installed, as in lab 1 setup. The rules tested here are PRICE-2 to PRICE-10 on its requirements page.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Make the project folders
Java: Maven's test folders, plus resources/features for the feature files. Python: a features/steps folder and a virtual environment.
# Java
mkdir -p shoprung-bdd/src/test/java/dev/algorung/steps shoprung-bdd/src/test/java/dev/algorung/support shoprung-bdd/src/test/resources/features
# Python
mkdir -p shoprung-bdd-py/features/steps && cd shoprung-bdd-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir -p shoprung-bdd/src/test/java/dev/algorung/steps shoprung-bdd/src/test/java/dev/algorung/support shoprung-bdd/src/test/resources/features
# Python
mkdir -p shoprung-bdd-py/features/steps && cd shoprung-bdd-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir shoprung-bdd\src\test\java\dev\algorung\steps, shoprung-bdd\src\test\java\dev\algorung\support, shoprung-bdd\src\test\resources\features
# Python
mkdir shoprung-bdd-py\features\steps; cd shoprung-bdd-py; py -m venv .venv; .venv\Scripts\Activate.ps1 The build file
Cucumber, its JUnit 5 engine and a JSON library, pinned to one version.
Create pom.xml. The Cucumber BOM (bill of materials) in dependencyManagement keeps every Cucumber module on 7.20.1, so you never mix versions. cucumber-java gives the step annotations, cucumber-junit-platform-engine lets JUnit 5 run feature files, cucumber-picocontainer shares state between step classes, and junit-platform-suite gives the runner annotations. Jackson reads ShopRung's JSON.
Python: behave is the Cucumber of Python, and httpx sends the HTTP calls. behave.ini hides the HTTP log lines and picks the readable pretty output.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>dev.algorung</groupId>
<artifactId>shoprung-cucumber</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-bom</artifactId>
<version>7.20.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit-platform-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
</plugins>
</build>
</project> - Import the BOM once; the Cucumber dependencies below then need no version.line 19
- The engine that turns each scenario into a JUnit test, so
mvn testruns them.line 42 - Dependency injection: one shared object per scenario, given to every step class (step 5).line 47
behave==1.3.3
httpx==0.28.1 [behave]
logging_level = WARNING
format = pretty - httpx logs every request at INFO; WARNING keeps the output to your scenarios.line 2
Python version of this step:
mvn -q dependency:resolve (no output: Maven downloaded the libraries)
pip install -r requirements.txt Successfully installed ... behave-1.3.3 ... httpx-0.28.1 ...
Write the coupon feature first
Business rules as examples anyone can read, before any code.
Create coupons.feature (Java: in src/test/resources/features/; Python: in features/). Read it aloud: it is the specification. Each Scenario is one example of a rule, written as Given (the situation), When (the action) and Then (the result). The Background runs before every scenario: fresh seed data and Alice logged in.
The Scenario Outline runs once per row of Examples, putting each row's values into <quantity> and <result>. That is how one readable scenario covers the boundary: 3 notebooks ($37.50) refused, 4 ($50.00) and 5 accepted. @smoke is a tag; you will use it in step 8.
Write the feature with the product owner or a developer in a "three amigos" session. The same file works in both languages, unchanged.
Feature: Coupons at checkout
As a shopper I want coupons to work exactly as advertised,
so that I pay the right amount. Rules PRICE-2 to PRICE-7.
Background:
Given the shop has its seed data
And I am logged in as "alice@shoprung.test"
@smoke
Scenario: SAVE10 applies at exactly $50.00
Given my cart has 4 "Clean Code Notebook"
When I apply the coupon "save10"
Then the coupon is accepted with "Coupon applied"
And the discount is "$5.00"
And the total is "$49.99"
Scenario Outline: SAVE10 needs a subtotal of $50.00 or more
Given my cart has <quantity> "Clean Code Notebook"
When I apply the coupon "SAVE10"
Then the coupon is <result>
Examples:
| quantity | result |
| 3 | refused |
| 4 | accepted |
| 5 | accepted |
Scenario: An expired coupon is refused
Given my cart has 1 "Testing Field Guide"
When I apply the coupon "WELCOME15"
Then the coupon is refused with "This coupon has expired"
Scenario: An unknown coupon is refused by name
Given my cart has 1 "Testing Field Guide"
When I apply the coupon "BOGUS"
Then the coupon is refused with "No coupon called BOGUS" - Steps every scenario in this file starts with.line 5
- Lower case on purpose: PRICE-2 says codes are not case-sensitive.line 12
- A template;
Examplesbelow gives one run per row.line 17 - Exactly $50.00: the boundary value that SAVE10 bugs usually break.line 25
Feature: Coupons at checkout
As a shopper I want coupons to work exactly as advertised,
so that I pay the right amount. Rules PRICE-2 to PRICE-7.
Background:
Given the shop has its seed data
And I am logged in as "alice@shoprung.test"
@smoke
Scenario: SAVE10 applies at exactly $50.00
Given my cart has 4 "Clean Code Notebook"
When I apply the coupon "save10"
Then the coupon is accepted with "Coupon applied"
And the discount is "$5.00"
And the total is "$49.99"
Scenario Outline: SAVE10 needs a subtotal of $50.00 or more
Given my cart has <quantity> "Clean Code Notebook"
When I apply the coupon "SAVE10"
Then the coupon is <result>
Examples:
| quantity | result |
| 3 | refused |
| 4 | accepted |
| 5 | accepted |
Scenario: An expired coupon is refused
Given my cart has 1 "Testing Field Guide"
When I apply the coupon "WELCOME15"
Then the coupon is refused with "This coupon has expired"
Scenario: An unknown coupon is refused by name
Given my cart has 1 "Testing Field Guide"
When I apply the coupon "BOGUS"
Then the coupon is refused with "No coupon called BOGUS" Python version of this step:
A runner, and the steps Cucumber asks for
Run the feature with no step code and let Cucumber write the method signatures.
Java: create RunCucumberTest.java. It has no code, only annotations: run the cucumber engine on every feature under features on the classpath, find step definitions in the package dev.algorung.steps (the glue), and write a pretty console log plus an HTML report.
Run it. Every step is undefined, so nothing passes, and Cucumber prints a ready-made snippet for each one with {int} and {string} already in place. Python: behave prints snippets too, but with the literal values; you will replace those with {quantity:d} and "{name}" placeholders in step 6.
package dev.algorung;
import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME;
import static io.cucumber.junit.platform.engine.Constants.PLUGIN_PROPERTY_NAME;
import org.junit.platform.suite.api.ConfigurationParameter;
import org.junit.platform.suite.api.IncludeEngines;
import org.junit.platform.suite.api.SelectClasspathResource;
import org.junit.platform.suite.api.Suite;
/** Tells JUnit 5 to run every .feature file under src/test/resources/features with Cucumber. */
@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "dev.algorung.steps")
@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty, html:target/cucumber.html")
public class RunCucumberTest {
} - Use the Cucumber engine, not the normal JUnit Jupiter one.line 13
- The glue: the package Cucumber searches for step definitions and hooks.line 3
- A one-file HTML report of every scenario after each run.line 16
mvn test Scenario: SAVE10 applies at exactly $50.00
Given the shop has its seed data
...
You can implement missing steps with the snippets below:
@Given("my cart has {int} {string}")
public void my_cart_has(Integer int1, String string) {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
} behave -f progress 0 features passed, 0 failed, 1 error, 0 skipped
0 scenarios passed, 0 failed, 6 error, 0 skipped
0 steps passed, 0 failed, 0 skipped, 32 undefined
You can implement step definitions for undefined steps with these snippets:
@given(u'the shop has its seed data')
def step_impl(context):
raise StepNotImplementedError(u'Given the shop has its seed data') A small ShopRung client
The HTTP details in one class, so step definitions stay one line each.
Create support/ShopRung.java (Python: shoprung.py in the project folder). It knows ShopRung's endpoints: reset, log in (and keep the token), find a product id by its name, add to cart, apply a coupon and read the cart. Steps will call these methods and never build a URL themselves.
Keeping this layer separate is the most important design choice in BDD suites: the same client can serve plain JUnit or pytest tests, and when an endpoint changes, you edit one method instead of twenty steps.
package dev.algorung.support;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
/** A small ShopRung API client. The steps call it, so they stay short and readable. */
public class ShopRung {
private static final String BASE_URL = System.getenv().getOrDefault("BASE_URL", "http://localhost:8080");
private static final Map<String, String> PASSWORDS = Map.of(
"alice@shoprung.test", "Alice123!",
"bob@shoprung.test", "Bob12345!");
private static final ObjectMapper JSON = new ObjectMapper();
private final HttpClient http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
private String token;
/** A status code and a parsed JSON body. */
public record Response(int status, JsonNode body) {
}
public void reset() {
send("POST", "/api/test/reset", null);
}
public void logIn(String email) {
Response r = send("POST", "/api/auth/login", Map.of("email", email, "password", PASSWORDS.get(email)));
if (r.status() != 200) {
throw new AssertionError("Login failed for " + email + ": " + r.body());
}
token = r.body().get("token").asText();
}
public int productId(String name) {
for (JsonNode product : send("GET", "/api/products", null).body().get("items")) {
if (product.get("name").asText().equals(name)) {
return product.get("id").asInt();
}
}
throw new AssertionError("ShopRung has no product called " + name);
}
public Response add(String name, int quantity) {
return send("POST", "/api/cart/items", Map.of("productId", productId(name), "quantity", quantity));
}
public Response applyCoupon(String code) {
return send("POST", "/api/cart/coupon", Map.of("code", code));
}
public JsonNode cart() {
return send("GET", "/api/cart", null).body();
}
private Response send(String method, String path, Object body) {
try {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(BASE_URL + path))
.header("Content-Type", "application/json")
.method(method, body == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)));
if (token != null) {
request.header("Authorization", "Bearer " + token);
}
HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
return new Response(response.statusCode(), JSON.readTree(response.body()));
} catch (IOException e) {
throw new UncheckedIOException("Is ShopRung running at " + BASE_URL + "?", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
} - Point the suite at another server with the BASE_URL environment variable.line 15
- Plain HTTP/1.1, which is what ShopRung speaks.line 21
- Features use product names, as people do; the client turns them into ids.line 40
- A clear message instead of a bare "connection refused".line 74
"""A small ShopRung API client. The steps call it, so they stay short and readable."""
import os
import httpx
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
PASSWORDS = {
"alice@shoprung.test": "Alice123!",
"bob@shoprung.test": "Bob12345!",
}
class ShopRung:
def __init__(self):
self.http = httpx.Client(base_url=BASE_URL, timeout=10)
def reset(self):
self.http.post("/api/test/reset").raise_for_status()
def log_in(self, email):
r = self.http.post("/api/auth/login", json={"email": email, "password": PASSWORDS[email]})
r.raise_for_status()
self.http.headers["Authorization"] = f"Bearer {r.json()['token']}"
def product_id(self, name):
for product in self.http.get("/api/products").json()["items"]:
if product["name"] == name:
return product["id"]
raise AssertionError(f"ShopRung has no product called {name!r}")
def add(self, name, quantity):
return self.http.post("/api/cart/items", json={"productId": self.product_id(name), "quantity": quantity})
def apply_coupon(self, code):
return self.http.post("/api/cart/coupon", json={"code": code})
def cart(self):
return self.http.get("/api/cart").json()
def close(self):
self.http.close() - After login, every request from this client carries Alice's token.line 23
- Names in features, ids in the API.line 25
Python version of this step:
Share state within one scenario
A fresh client and "last response" per scenario, never static fields.
Steps run one after another, and later steps need what earlier steps produced: the When step stores the coupon response, the Then step checks it. Java: create support/World.java. PicoContainer creates a new World for every scenario and passes the same instance to every step class that asks for it in its constructor. Never use static fields for this: they leak between scenarios and break parallel runs.
Python: behave gives every step a context object for this. Create features/environment.py, where hooks live: before_scenario gives each scenario a new client, and after_scenario closes it.
package dev.algorung.support;
/**
* State shared by the steps of ONE scenario. PicoContainer creates a new World for every scenario
* and passes the same instance to every step class that asks for it in its constructor.
*/
public class World {
public final ShopRung shop = new ShopRung();
public ShopRung.Response last;
} - A new client, and so a new login, for each scenario.line 8
- The latest response, for the Then steps to check.line 9
"""behave hooks: a fresh client for every scenario, closed afterwards."""
from shoprung import ShopRung
def before_scenario(context, scenario):
context.shop = ShopRung()
def after_scenario(context, scenario):
context.shop.close() - behave calls this before every scenario, Background included.line 5
Python version of this step:
Step definitions
Glue every Gherkin line to one client call and one check.
Create steps/CheckoutSteps.java (Python: features/steps/checkout_steps.py). Each method has an annotation (decorator) whose Cucumber expression matches step text: {int} and {string} become method parameters, converted for you. behave uses the same idea with {quantity:d} for numbers and "{name}" for quoted text.
One definition can serve many steps. the {word} is {string} checks the subtotal, discount, shipping and total by reading that field from the cart. The coupon steps check both the status code and the exact message from the requirements.
Run only the coupon feature: all 6 scenarios pass, including the 3 rows of the outline.
package dev.algorung.steps;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.algorung.support.World;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.util.List;
import java.util.Map;
/** Step definitions for coupons.feature and shipping.feature. Each step is one call and one check. */
public class CheckoutSteps {
private final World world;
public CheckoutSteps(World world) {
this.world = world;
}
@Given("the shop has its seed data")
public void theShopHasItsSeedData() {
world.shop.reset();
}
@Given("I am logged in as {string}")
public void iAmLoggedInAs(String email) {
world.shop.logIn(email);
}
@Given("my cart has {int} {string}")
public void myCartHas(int quantity, String name) {
world.last = world.shop.add(name, quantity);
assertEquals(200, world.last.status(), world.last.body().toString());
}
@Given("my cart contains:")
public void myCartContains(List<Map<String, String>> rows) {
for (Map<String, String> row : rows) {
world.last = world.shop.add(row.get("product"), Integer.parseInt(row.get("quantity")));
assertEquals(200, world.last.status(), world.last.body().toString());
}
}
@When("I apply the coupon {string}")
public void iApplyTheCoupon(String code) {
world.last = world.shop.applyCoupon(code);
}
@Then("the coupon is accepted with {string}")
public void theCouponIsAcceptedWith(String message) {
assertEquals(200, world.last.status(), world.last.body().toString());
assertEquals(message, world.last.body().get("coupon").get("message").asText());
}
@Then("the coupon is accepted")
public void theCouponIsAccepted() {
assertEquals(200, world.last.status(), world.last.body().toString());
}
@Then("the coupon is refused with {string}")
public void theCouponIsRefusedWith(String message) {
int status = world.last.status();
assertTrue(status == 400 || status == 404, "expected 400 or 404, got " + status);
assertEquals(message, world.last.body().get("message").asText());
}
@Then("the coupon is refused")
public void theCouponIsRefused() {
assertEquals(400, world.last.status(), world.last.body().toString());
}
@Then("the {word} is {string}")
public void theAmountIs(String field, String amount) {
assertEquals(amount, world.shop.cart().get(field).asText(), field);
}
} - PicoContainer passes in this scenario's World.line 17
- Matches
my cart has 4 "Clean Code Notebook": quantity 4, name without quotes.line 31 - ShopRung answers 400 for an expired coupon and 404 for an unknown one.line 64
- One step for four fields: subtotal, discount, shipping, total.line 73
"""Step definitions for coupons.feature and shipping.feature. Each step is one call to the client and one check."""
from behave import given, then, when
@given("the shop has its seed data")
def reset(context):
context.shop.reset()
@given('I am logged in as "{email}"')
def log_in(context, email):
context.shop.log_in(email)
@given('my cart has {quantity:d} "{name}"')
def add_one(context, quantity, name):
r = context.shop.add(name, quantity)
assert r.status_code == 200, r.text
context.response = r
@given("my cart contains:")
def add_table(context):
for row in context.table:
r = context.shop.add(row["product"], int(row["quantity"]))
assert r.status_code == 200, r.text
context.response = r
@when('I apply the coupon "{code}"')
def apply_coupon(context, code):
context.response = context.shop.apply_coupon(code)
@then('the coupon is accepted with "{message}"')
def accepted_with(context, message):
assert context.response.status_code == 200, context.response.text
assert context.response.json()["coupon"]["message"] == message
@then("the coupon is accepted")
def accepted(context):
assert context.response.status_code == 200, context.response.text
@then('the coupon is refused with "{message}"')
def refused_with(context, message):
assert context.response.status_code in (400, 404), context.response.text
assert context.response.json()["message"] == message
@then("the coupon is refused")
def refused(context):
assert context.response.status_code == 400, context.response.text
@then('the {field} is "{amount}"')
def amount_is(context, field, amount):
actual = context.shop.cart()[field]
assert actual == amount, f"{field}: expected {amount}, got {actual}" :dconverts the number to an int.line 15- Stored on
contextfor the Then step.line 32 - One step for subtotal, discount, shipping and total.line 57
Python version of this step:
mvn test -Dcucumber.features=classpath:features/coupons.feature [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
behave -f progress features/coupons.feature 1 feature passed, 0 failed, 0 skipped 6 scenarios passed, 0 failed, 0 skipped 32 steps passed, 0 failed, 0 skipped
Stuck on this step?
- Java: "Step ... is defined with 2 parameters but the step has 1 argument" or similar.
- The expression and the method do not agree. Each
{int}or{string}needs one parameter, in the same order. - Java: "AmbiguousStepDefinitionsException".
- Two expressions match the same text. Make one more specific, for example add "with {string}".
- Python: a step matches with the quotes inside the value.
- Put the quotes in the pattern, outside the placeholder:
"{name}", not{name}.
Data tables and the shipping rule
A cart of several products in one readable step, and the $75.00 boundary.
Create shipping.feature. The first scenario fills the cart with a data table: 4 notebooks ($50.00), a T-shirt ($20.00) and a sticker pack ($4.99), $74.99 in total, one cent below free shipping. So shipping is $4.99 and the total $79.98. The outline then checks both sides of the boundary: 5 notebooks ($62.50) pay shipping, 6 ($75.00) ship free.
The table step already exists: in Java, my cart contains: receives the table as a List<Map<String, String>>, one map per row keyed by the header; in Python, context.table gives rows you index by column name. Run everything: 9 scenarios.
Feature: Shipping and totals
Shipping is free when the subtotal after the discount is $75.00 or more,
otherwise it is $4.99. Total = subtotal - discount + shipping. Rules PRICE-9, PRICE-10.
Background:
Given the shop has its seed data
And I am logged in as "alice@shoprung.test"
Scenario: A mixed cart one cent below $75.00 pays shipping
Given my cart contains:
| product | quantity |
| Clean Code Notebook | 4 |
| Ship It T-Shirt | 1 |
| Sticker Pack: Edge Cases | 1 |
Then the subtotal is "$74.99"
And the shipping is "$4.99"
And the total is "$79.98"
Scenario Outline: Free shipping starts at exactly $75.00
Given my cart has <quantity> "Clean Code Notebook"
Then the subtotal is "<subtotal>"
And the shipping is "<shipping>"
Examples:
| quantity | subtotal | shipping |
| 5 | $62.50 | $4.99 |
| 6 | $75.00 | $0.00 | - The header row: these names become the map keys.line 11
- Checked by the same
the {word} is {string}step as the coupon totals.line 15 - Exactly $75.00 ships free (PRICE-9).line 27
Feature: Shipping and totals
Shipping is free when the subtotal after the discount is $75.00 or more,
otherwise it is $4.99. Total = subtotal - discount + shipping. Rules PRICE-9, PRICE-10.
Background:
Given the shop has its seed data
And I am logged in as "alice@shoprung.test"
Scenario: A mixed cart one cent below $75.00 pays shipping
Given my cart contains:
| product | quantity |
| Clean Code Notebook | 4 |
| Ship It T-Shirt | 1 |
| Sticker Pack: Edge Cases | 1 |
Then the subtotal is "$74.99"
And the shipping is "$4.99"
And the total is "$79.98"
Scenario Outline: Free shipping starts at exactly $75.00
Given my cart has <quantity> "Clean Code Notebook"
Then the subtotal is "<subtotal>"
And the shipping is "<shipping>"
Examples:
| quantity | subtotal | shipping |
| 5 | $62.50 | $4.99 |
| 6 | $75.00 | $0.00 | Python version of this step:
mvn test [INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
behave -f progress 2 features passed, 0 failed, 0 skipped 9 scenarios passed, 0 failed, 0 skipped 48 steps passed, 0 failed, 0 skipped
Tags, reports and a dry run
Run a subset, keep a report, and check every step has code without running anything.
Tags select scenarios. Run only @smoke: one scenario. Tag expressions combine with and, or and not, for example @smoke and not @wip.
Reports: Java writes target/cucumber.html on every run (open it in a browser). behave writes JUnit XML files with --junit into reports/, which CI tools show as a test tab.
A dry run checks that every step has a definition without calling ShopRung: a cheap check to run in CI before the real suite.
mvn test -Dcucumber.filter.tags="@smoke"
mvn test -Dcucumber.execution.dry-run=true [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
behave -f progress --tags=@smoke
behave -f progress --junit
behave --dry-run 1 feature passed, 0 failed, 1 skipped 1 scenario passed, 0 failed, 8 skipped 7 steps passed, 0 failed, 41 skipped ... (reports/TESTS-coupons.xml and reports/TESTS-shipping.xml) ... 0 scenarios passed, 0 failed, 0 skipped, 9 untested
Check it works
Switch on ShopRung's coupon-boundary bug and run the suite: exactly 2 scenarios fail, SAVE10 applies at exactly $50.00 and the outline row with 4 notebooks. The failure shows ShopRung's own reason: "This coupon needs a subtotal of at least $50.00".
Then try expired-coupon (only "An expired coupon is refused" fails) and free-shipping-boundary (only the 6-notebook row of the shipping outline fails). search-case changes nothing: no scenario searches. Each bug fails exactly the scenario that describes its rule, which is what makes a BDD suite useful to read. Turn the bugs off at the end.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
behave -f progress # or: mvn test Failing scenarios:
features/coupons.feature:10 SAVE10 applies at exactly $50.00
features/coupons.feature:25 SAVE10 needs a subtotal of $50.00 or more -- @1.2
7 scenarios passed, 2 failed, 0 skipped
(the pretty output shows)
Then the coupon is accepted with "Coupon applied"
ASSERT FAILED: {"error":"coupon_not_applicable","message":"This coupon needs a subtotal of at least $50.00"} Troubleshooting
Java: mvn test runs 0 tests.
The runner class must end in Test (Surefire's default) and the features must be under src/test/resources/features, matching @SelectClasspathResource("features").
Every step is undefined though the step class exists.
Java: the glue package in the runner must match the package of CheckoutSteps. Python: step files must be in features/steps/.
Java: "NoSuchMethodException ... CheckoutSteps.()" or World is null.
cucumber-picocontainer is missing from the pom, so Cucumber cannot pass a World to the constructor.
A scenario fails only when run with others.
Something is shared between scenarios: a static field, or a missing reset. Each scenario must start from the Background.
ConnectException or "Is ShopRung running at http://localhost:8080?"
Start ShopRung, or set BASE_URL to the address it runs on.
What changes in production
- Feature files are written with the product owner and kept next to the code; the scenarios double as living documentation of the rules.
- Step definitions stay thin and call a client or page objects; teams often reuse the same client in plain JUnit or pytest tests.
- CI runs a dry run, then
@smokeon every pull request and the full feature set nightly, publishing the HTML or JUnit report. - Cucumber scenarios run in parallel only when they share nothing: own data, own user, no static state.
Interview angle
โHow do you structure a Cucumber framework?โ
Feature files under resources, written with the business as examples of rules, with Background for shared setup, Scenario Outlines for boundaries and data tables for richer input. A JUnit 5 suite runner sets the glue and report plugins. Step definitions are thin: each calls a client or page object layer and makes one assertion, using Cucumber expressions for parameters. State is shared per scenario through dependency injection such as PicoContainer, never static fields. Tags select smoke runs, a dry run checks every step has code, and reports go to CI.
Clean up
Practice
These run in your browser and check your answer.
Match a Cucumber expression
Cucumber turns {int} and {string} into regular expressions. Write match_step(expression, text): return the list of values (ints for {int}, strings without quotes for {string}), or None when the text does not match.
import re
def match_step(expression, text):
parts = re.split(r"(\{int\})", expression)
pattern, kinds = "", []
for part in parts:
if part == "{int}":
pattern += r"(-?\d+)"
kinds.append(int)
else:
pattern += re.escape(part)
m = re.fullmatch(pattern, text)
if m is None:
return None
return [kind(value) for kind, value in zip(kinds, m.groups())]
Hint
Split on both placeholders with `(\{int\}|\{string\})`, and turn `{string}` into `"([^"]*)"` so the quotes are matched but not captured.
The full project
Every file from this lab, as it is after the last step.