Cucumber and BDD interview questions
Updated 2026-11-13 · 11 min read
Thirty Cucumber and BDD interview questions with practical examples. Covers executable scenarios, Java glue, isolated state and honest tradeoffs for test teams.
Use a concrete rule to explain BDD: a customer's cart subtotal must reflect the selected quantity. The important discussion is which examples make that rule clear, not how many feature files the team owns.
BDD and readable examples
1. What is behaviour-driven development?
BDD is a collaborative approach to discovering and describing the behaviour a product should have. People with business, development and testing knowledge work through concrete examples before implementing a rule. For an OTP flow, that discussion might reveal whether requesting a second OTP invalidates the first; automation then checks the agreed examples.
2. What is Cucumber's role in BDD?
Cucumber executes scenarios written in Gherkin by matching their steps to code. It supports automation and feedback, but it cannot create collaboration on its own. A team that writes feature files only after development may have useful automated tests while missing BDD's earlier discovery work.
3. How do BDD and TDD differ?
TDD uses a failing test to guide a small implementation change; BDD emphasises shared understanding of behaviour through examples. They can work together: an agreed checkout example guides the feature while unit tests guide its internal calculation code. Avoid claiming they are competing tools or that BDD removes the need for lower-level tests.
4. What belongs in a feature file?
A Feature names a capability and contains scenarios illustrating its rules. Optional descriptions explain purpose, and Rule can group examples of a particular business rule. Keep the file coherent: mixing login lockout and invoice rounding under a vague feature called Testing makes review and failure ownership harder.
5. What do Given, When and Then mean?
Given describes the starting context, When the action or event, and Then an observable result. And and But improve readability when several steps have the same role. A Then should assert something meaningful; a step that only prints the cart total can pass even when the total is wrong.
6. How do you write a short Gherkin scenario?
This scenario focuses on a subtotal rule without prescribing button clicks. Amounts are in paise, so the example has no ambiguity about decimal rounding.
Feature: Cart subtotal
Scenario: Two units contribute twice the unit price
Given an item costs 14900 paise
When I calculate the subtotal for 2 units
Then the subtotal is 29800 paise
In a real application test, the calculation step should invoke the application's domain code or API. A duplicate calculation in glue can only prove the example's own arithmetic.
7. What makes a scenario too technical?
Selectors, sleeps and a long sequence of clicks usually obscure the business rule. Prefer an action such as requesting a password reset over naming every input field's CSS selector. Keep the details inside automation helpers, while retaining any detail that changes behaviour, such as an expired OTP or a different account owner.
8. How do you discover good examples before coding?
Ask for a normal case, a boundary and a counterexample, then resolve conflicting expectations. For a coupon minimum, clarify whether the threshold applies before tax and whether equality qualifies. Record the agreed outcomes so the scenario is a decision the team shares, not a guess made by the automation author.
Likely follow-up: Who should write the scenarios? Anyone can draft them, but the people who understand the rule and implementation should review them together. Ownership by only the automation tester defeats much of the purpose.
Step definitions and data
9. What is a step definition?
It is code with an expression that matches a Gherkin step's text. Cucumber converts captured arguments and calls that method. The following Java glue corresponds to question 6 and uses instance fields for this scenario's values.
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import org.testng.Assert;
public class SubtotalSteps {
private int price;
private int subtotal;
@Given("an item costs {int} paise")
public void priceIs(int price) {
this.price = price;
}
@When("I calculate the subtotal for {int} units")
public void calculate(int quantity) {
subtotal = price * quantity;
}
@Then("the subtotal is {int} paise")
public void subtotalIs(int expected) {
Assert.assertEquals(subtotal, expected);
}
}
The TestNG assertion library here supplies assertions; it does not select a Cucumber runner automatically.
10. What is a Cucumber Expression?
It is a readable matching expression with parameter types such as {int} and {string}. {string} captures quoted text; {int} converts a matching integer to an integer argument. Prefer specific domain language over a catch-all expression that could accidentally match unrelated login and payment steps.
11. How do undefined and ambiguous steps differ?
An undefined step has no matching definition; an ambiguous one matches more than one. For undefined steps, check the expression and glue package discovery before adding new code. For ambiguity, remove overlapping definitions or sharpen the language; moving identical definitions to different classes does not resolve the collision.
12. Does changing Given to Then create a different step definition?
Cucumber matches the step text without treating the Gherkin keyword as a separate namespace. Two definitions for the same text can conflict even if one uses @Given and the other @Then. Use language that distinguishes setup from verification, such as a cart containing two items versus asserting that the cart displays two items.
13. What is a Scenario Outline?
It is a scenario template expanded once per row in an Examples table. Each row becomes a separately executed example with its own lifecycle. Use it when the same rule and steps apply to several inputs, rather than copying nearly identical scenarios.
Feature: Cart subtotal examples
Scenario Outline: Quantity determines subtotal
Given an item costs 14900 paise
When I calculate the subtotal for <quantity> units
Then the subtotal is <subtotal> paise
Examples:
| quantity | subtotal |
| 1 | 14900 |
| 2 | 29800 |
| 3 | 44700 |
14. How does a data table differ from Examples?
An Examples table expands a Scenario Outline into multiple executions. A data table is an argument passed to one step in one execution, for example several line items in a single cart. If each row needs an independent pass or fail result, an outline is usually the clearer choice.
15. How do you read a data table in Java?
Receive io.cucumber.datatable.DataTable as the step's final argument and convert it with methods such as asMaps(String.class, String.class). A header row can name productId and qty, with each subsequent row representing one item. Parse and validate quantities explicitly so an invalid fixture produces a useful error instead of a mysterious checkout mismatch.
16. When would you use a Doc String?
Use a Doc String for a multiline argument such as a JSON request body or a block of expected text. It is passed to the step rather than becoming several separate steps. Keep large technical payloads in fixture files when they drown out the behaviour; show only the fields essential to the example in the feature file.
Hooks, tags and state
17. What is Background?
Background contains readable context shared by the scenarios in its feature or rule. Its steps run before each scenario, after before hooks. Use it for context a stakeholder needs to understand, such as an existing signed-in customer; a long background full of unrelated setup makes every scenario harder to follow.
18. How does Background differ from a before hook?
Background is visible Gherkin explaining business context. A before hook is code suitable for technical setup such as creating a browser or clearing a scenario-owned context. Do not hide a crucial business assumption, such as a customer's credit limit, in a hook where reviewers cannot see it.
19. What do Cucumber hooks do?
io.cucumber.java.Before and After run around scenarios, while step hooks can observe individual steps. They are Cucumber annotations, distinct from similarly named annotations in other test frameworks. Capture failure evidence before closing the browser and make teardown safe when setup only partly completed.
20. How do you apply a hook to selected scenarios?
Use a tag expression on a hook, for example @Before("@ui") for browser setup. API-only scenarios then avoid paying for an unused browser. Keep hook conditions simple and inspect inherited tags, because a feature-level tag can cause every scenario in the file to receive that setup.
21. What are tags used for?
Tags label scenarios, features or example groups for selection, hooks and reporting. A tag expression such as @smoke and not @wip selects a deliberate subset. A tag is not proof of coverage: regularly check that the smoke selection still includes the critical login and checkout rules.
22. How do you share state between step classes safely?
Use a scenario-scoped context supplied through a supported dependency-injection integration. It can hold that scenario's token, response and resource ids. Avoid static mutable fields: one scenario can overwrite another's token, particularly when execution becomes parallel.
23. Can scenarios depend on each other?
They should be independently executable, with their own context and data. A second scenario must not rely on a first one having created an order or left a browser signed in. If several actions form one meaningful business example, keep them in one scenario rather than relying on file order.
24. How do you avoid a step-definition maintenance problem?
Organise glue around domain concepts and delegate API calls or page operations to helpers. Reuse steps when their meaning is identical, not merely when their words look similar. A universal step accepting arbitrary method names or assertions creates a programming language in Gherkin that business reviewers cannot usefully review.
Runners, reports and practical decisions
25. What does the Cucumber runner configure?
It connects feature discovery, glue discovery, filters and output plugins to a test execution platform. Java projects may use JUnit Platform, a JUnit 4 adapter or a TestNG integration; their configuration styles differ. Choose one compatible integration and confirm it discovers scenarios before adding parallel settings.
26. How do you configure a small TestNG-based runner?
This example needs compatible cucumber-java and cucumber-testng dependencies plus TestNG. Put feature files under src/test/resources/features and glue classes in the qa.steps package.
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
@CucumberOptions(
features = "src/test/resources/features",
glue = "qa.steps",
tags = "@smoke and not @wip",
plugin = {"pretty", "html:target/cucumber.html", "junit:target/cucumber.xml"}
)
public class RunCucumberTest extends AbstractTestNGCucumberTests {
}
The arithmetic scenario above needs a @smoke tag to be selected by this runner. An empty filtered run is not evidence that the scenario passed.
27. How do you report failures usefully?
Retain machine-readable results for CI and a readable scenario report for people. Attach sanitised screenshots or response details using the scenario API where appropriate, and include the revision and environment. A red step with no actual value, request or screenshot often forces someone to rerun the suite just to begin diagnosis.
28. What must change before running scenarios in parallel?
Isolate accounts, resource ids, browsers and output files, then enable parallel execution using the chosen runner's supported configuration. The TestNG adapter and JUnit Platform do not use identical switches. A separate Java object per scenario does not isolate the server's shared cart or prevent one scenario's reset call from erasing another's order.
29. When is BDD worth the effort?
It is valuable when rules have ambiguity and examples help several roles agree on outcomes, such as coupon eligibility or booking cancellation fees. The team must actually review and maintain those examples. A smaller set of trusted behaviour scenarios is more useful than hundreds of generated feature files nobody reads.
30. When would you choose plain test code instead?
Use ordinary unit or API tests for detailed technical checks where a second prose layer adds little shared understanding. For example, exhaustively checking a parser's invalid inputs may be clearer with a parameterized test. Keep BDD for behaviour discussions where it earns its maintenance cost; do not promise that adopting Cucumber automatically improves coverage or removes flaky browser tests.
Practise it
Choose one cart rule in ShopLite, write a normal example and a boundary example, and ask someone else to predict their outcomes before automating. Bind the steps to its API, then prove the scenarios run independently. Use the API testing questions to choose meaningful assertions.
Quick answers
Is BDD the same as writing Given, When and Then?
No. BDD involves discovering behaviour together, agreeing examples and using them to guide implementation. Gherkin is one way to record those examples.
Does Cucumber require Selenium?
No. Steps can call domain code, API clients or browser automation depending on the behaviour being checked.
Should every test become a feature scenario?
No. Use scenarios for behaviour worth discussing with stakeholders. Keep detailed technical checks in ordinary tests when that is clearer.
Sources
Want a project you can show in interviews?
The portfolio project kit walks you through testing a deliberately buggy app with Selenium or Playwright and API tests, then explaining it. The app itself is free.
