Resource library

QA Interview

Top 30 Cucumber Interview Questions and Answers (2026)

Prepare the top Cucumber interview questions with 30 expert answers on BDD, Gherkin, step definitions, hooks, tags, DataTables, frameworks, and CI in 2026.

31 min read | 3,231 words

TL;DR

The best Cucumber answers show that BDD is a collaboration practice, Gherkin expresses rules through examples, and Cucumber executes those examples through thin step definitions. Prepare to discuss scenario design, transformations, hooks, tags, state isolation, UI and API integration, CI, and when ordinary test code is clearer.

Key Takeaways

  • Separate BDD collaboration, Gherkin specifications, Cucumber execution, and automation drivers.
  • Write concrete scenarios around business rules and observable outcomes instead of UI procedures.
  • Keep step definitions thin and delegate behavior to scenario-safe domain or automation services.
  • Use Scenario Outlines and DataTables only when their structure improves rule understanding.
  • Reserve hooks for technical lifecycle work and keep business context visible in Gherkin.
  • Run scenarios independently with scoped state, governed tags, run-owned data, and complete evidence.
  • Choose Cucumber when executable examples improve cross-role communication enough to justify glue cost.

These top Cucumber interview questions prepare QA and SDET candidates to explain behavior-driven development, Gherkin, executable specifications, step-definition design, data modeling, hooks, tags, reporting, and CI. The key distinction is simple: Cucumber is most valuable as a collaboration and specification tool, not as a way to translate every manual click into English-like automation.

The 30 answers below focus on Cucumber-JVM examples while keeping the BDD principles portable. A credible response connects a business example to a clear rule, a thin automation boundary, a meaningful failure, and a team conversation. It also knows when plain test code is the better choice.

TL;DR

Topic Interview-ready answer
BDD A discovery and delivery practice built around concrete examples and shared language
Gherkin A structured language for readable rules and examples, not a procedural scripting language
Step definitions Small adapters from domain phrases to automation code
Scenario Outline Repeats one rule with a concise examples table
DataTable Supplies structured domain data when a row or table is clearer than many parameters
Hooks Handle technical lifecycle concerns, not hidden business steps
Tags Express meaningful suite metadata and selection policy
Success measure Better shared understanding and useful executable evidence, not feature-file count

1. How to Prepare for the Top Cucumber Interview Questions

Practice three types of answers. First, define BDD, Gherkin, and Cucumber separately. Second, transform a vague requirement into rules and examples. Third, review an unhealthy suite with duplicated steps, UI details, large backgrounds, and hidden hooks. This shows that you understand both authoring and governance.

Use one business rule as your portfolio example. For a discount, document eligibility, boundaries, exclusions, and rounding. Discuss it with product and development perspectives, write concise scenarios, implement the rule below the UI where possible, and keep one higher-level journey if user wiring matters. The feature should remain readable even when the automation technology changes.

Answer with domain language. When the customer submits an order worth $50 is usually better than When I click the green submit button after typing 50. The first expresses behavior. The second freezes a particular interface procedure inside the specification. A UI-specific scenario is appropriate only when the UI interaction itself is the behavior under discussion.

Study writing acceptance criteria with AI for rule discovery and decision table testing for systematic example selection.

2. Explain BDD, Gherkin, and Cucumber Precisely

BDD is a collaborative approach to discovering and delivering behavior through examples. Teams explore rules before or during implementation, build a shared domain language, and use examples to expose ambiguity. Some examples become automated checks, but automation is an outcome, not the definition of BDD.

Gherkin is the structured language used in feature files. Keywords such as Feature, Rule, Scenario, Given, When, Then, Background, Scenario Outline, and Examples organize intent and examples. Cucumber parses Gherkin, matches steps to step definitions, executes supporting code, and reports scenarios.

Keep the layers distinct in an interview:

Layer Purpose Common mistake
BDD practice Discover rules and align people Calling a test runner the whole practice
Gherkin Express behavior with examples Writing low-level automation procedures
Cucumber runtime Match and execute steps Putting domain logic in glue code
Automation libraries Drive APIs, browsers, databases, or fakes Letting tool mechanics leak into every scenario

Three Amigos conversations commonly bring product, development, and testing perspectives together. The purpose is not a mandatory meeting format. It is to resolve examples, assumptions, and edge cases early enough to change the solution cheaply.

3. Write Gherkin That Describes Rules, Not Clicks

A useful feature has a clear capability, optional business rules, and scenarios that illustrate distinct behavior. Given describes relevant context, When describes the triggering event, and Then describes an observable outcome. These words do not impose a technical execution layer. A Given can use an API fixture behind the scenes even if the final Then observes the UI.

This feature is valid Gherkin and can run with matching step definitions:

Feature: Free standard shipping

  Rule: Eligible domestic orders receive free standard shipping

    Scenario Outline: Shipping eligibility at the order boundary
      Given a domestic customer has an order worth <orderTotal>
      When the customer reviews shipping options
      Then standard shipping should cost <shippingCost>

      Examples:
        | orderTotal | shippingCost |
        | 49.99      | 5.00         |
        | 50.00      | 0.00         |
        | 75.00      | 0.00         |

    Scenario: International orders are excluded
      Given an international customer has an order worth 75.00
      When the customer reviews shipping options
      Then standard shipping should cost 12.00

The values sit at a meaningful boundary, and the exclusion receives its own named scenario. Avoid And the user clicks chains that reconstruct a test script. Avoid a scenario that validates five rules and fails without showing which rule broke. Keep business terminology consistent with the product model.

4. Implement Thin, Reusable Step Definitions

Step definitions are adapters. They convert a domain phrase and its arguments into calls to application drivers, domain services, or test context. They should not contain large conditional workflows or duplicate product calculations. Reuse comes from consistent domain language and well-designed code below the steps, not from vague phrases such as When I perform action with data.

The following Cucumber-JVM step class uses current Java annotations and a typed parameter. The ShippingQuoteClient is an application-specific interface that a real test implementation supplies.

package examples.shipping;

import io.cucumber.java.ParameterType;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.math.BigDecimal;

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

public final class ShippingSteps {
  private final ScenarioState state;
  private final ShippingQuoteClient client;

  public ShippingSteps(ScenarioState state, ShippingQuoteClient client) {
    this.state = state;
    this.client = client;
  }

  @ParameterType("\\d+\\.\\d{2}")
  public BigDecimal money(String value) {
    return new BigDecimal(value);
  }

  @Given("a domestic customer has an order worth {money}")
  public void domesticOrder(BigDecimal total) {
    state.setRequest(new ShippingRequest("US", total));
  }

  @When("the customer reviews shipping options")
  public void reviewShippingOptions() {
    state.setQuote(client.quote(state.getRequest()));
  }

  @Then("standard shipping should cost {money}")
  public void standardShippingCosts(BigDecimal expected) {
    assertEquals(expected, state.getQuote().standardPrice());
  }
}

Dependency injection and scenario-scoped state should prevent data leaking between scenarios. Do not make state static.

5. Use Scenario Outlines, Data Tables, and Transformations Well

A Scenario Outline repeats the same scenario structure for each row in Examples. Use it when rows express equivalent examples of one rule. If rows represent different rules or deserve different names and discussion, separate scenarios are clearer. Adding 100 spreadsheet rows can make reports unreadable and may signal that a lower-level parameterized test is more appropriate.

A DataTable passes a table to one step. It works well for a cart, form, role matrix, or other structured domain object. Cucumber-JVM exposes io.cucumber.datatable.DataTable, which can be converted using methods such as asMaps when the headers and values are strings.

import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import java.util.List;
import java.util.Map;

@Given("the cart contains these products")
public void cartContainsProducts(DataTable table) {
  List<Map<String, String>> rows = table.asMaps(String.class, String.class);
  for (Map<String, String> row : rows) {
    cartApi.add(
        row.get("sku"),
        Integer.parseInt(row.get("quantity")));
  }
}

Custom parameter types and data-table transformations centralize parsing and validation. Reject invalid inputs early with a useful message. Do not hide a complex object graph behind a cryptic table simply to make a feature shorter. The representation should help a domain reader reason about the rule.

6. Control Hooks, Backgrounds, Tags, and State

Hooks run around scenarios and are appropriate for technical lifecycle concerns such as starting a browser context, opening a transaction, capturing failure evidence, or releasing resources. They are not a place to hide essential business setup. If a customer must have a premium subscription for the rule, state that context in Gherkin.

Background runs before each scenario in a feature or rule and should contain only short context shared by every scenario in that scope. Large backgrounds make readers scroll to understand each example. Prefer a Rule with focused scenarios or direct Given steps when context differs.

Tags attach metadata to features, rules, scenarios, outlines, or examples. Use domain or suite policy such as @payments, @smoke, @destructive, or @requires-real-provider. Tag expressions select combinations. Avoid tags that encode changing organization charts or become an ungoverned list of aliases.

State must be scenario-scoped. Static fields, singleton world objects, reused browser storage, and shared database records create order dependence and parallel failures. A hook may capture a screenshot on failure, but the report also needs scenario identity, logs, request evidence, and environment details. Cleanup should run even when a step fails, and it should remove only resources created by that scenario.

7. Integrate Cucumber With UI, API, and CI Automation

Cucumber does not replace a browser or API library. Step definitions call Playwright, Selenium, REST Assured, application clients, or domain test doubles. Keep that technology behind clear adapters so feature language remains stable. A business scenario may create data through an API, exercise a browser action, and verify a message through another supported interface when that is the behavior being proven.

Choose execution layers deliberately. A pricing rule with dozens of combinations is usually cheaper as a unit or service test. A few Gherkin examples can remain as living documentation for the most important rules. A critical checkout journey can use UI automation. The same example does not need to be repeated through every layer.

In CI, publish Cucumber reports and underlying artifacts, return a blocking exit code for failed scenarios, and shard only independent scenarios. Record feature revision, application build, tag expression, environment, and runtime versions. Reruns must not erase the first failure. Undefined, ambiguous, and pending steps are not successful coverage.

Treat living documentation as a maintained product. Remove obsolete examples, review terminology, link rules to current domain decisions, and make reports accessible to the people who use them. Cypress data-cy selector guidance can help keep browser mechanics out of feature text.

8. Review the Top Cucumber Interview Questions as a Senior SDET

Senior candidates should recognize Cucumber failure modes. Step explosion occurs when every wording variation creates new glue. Regex or expression ambiguity occurs when two definitions match the same phrase. Slow suites emerge when every Given uses a full browser journey. Unreadable features emerge when teams prioritize step reuse over coherent domain sentences.

Govern the suite with conventions:

  • One shared domain glossary for important terms.
  • Features organized by capability, not by page.
  • Short scenarios focused on one rule or outcome.
  • Thin steps calling reusable code below the glue layer.
  • Scenario-scoped dependencies and run-owned data.
  • Tags with documented selection semantics.
  • Reports that distinguish assertion, undefined step, setup, infrastructure, and cleanup failures.
  • Regular deletion or migration of examples that no longer provide documentation value.

Know when not to use Cucumber. Developer-facing algorithms, dense combinatorial checks, technical protocol contracts, and tests with no cross-role readership can be clearer in ordinary code. Cucumber earns its cost when readable examples improve shared understanding and remain useful as executable documentation.

Interview Questions and Answers

Q1: What is Cucumber?

Cucumber is a tool that parses Gherkin feature files, matches steps to step definitions, runs supporting automation code, and reports scenario outcomes. It supports executable specifications in a BDD workflow. It is not itself the browser driver, API client, or full definition of BDD.

Q2: What is behavior-driven development?

BDD is a collaborative practice for discovering and delivering software behavior through concrete examples and shared language. Product, development, and testing perspectives clarify rules and edge cases before misunderstandings become code. Selected examples can become executable specifications, but conversation and discovery remain central.

Q3: What is Gherkin?

Gherkin is a structured, business-readable language used in feature files. Keywords organize capabilities, rules, examples, context, events, and outcomes. Its value comes from clear domain examples, not from making automation code look like natural language.

Q4: Explain Given, When, and Then.

Given establishes relevant context, When describes the event or action, and Then states an observable outcome. And and But improve readability without creating new semantics. These keywords do not require UI implementation, so a Given can set state through an API.

Q5: What is a step definition?

A step definition binds a Cucumber expression or regular expression to executable code. It converts captured values and delegates to domain or automation services. Good step definitions are thin, diagnostic, and scenario-safe. Business rules should not be duplicated inside glue code.

Q6: What is the difference between a Scenario and a Scenario Outline?

A Scenario is one concrete example. A Scenario Outline is a template executed once for each Examples row. I use an outline for equivalent data variations of one rule and separate scenarios when cases express different rules or deserve individual names.

Q7: What is a DataTable?

A DataTable supplies structured tabular data to a step. Cucumber-JVM can expose it as a DataTable and transform it into lists, maps, or domain objects. It is useful when the table improves understanding, not merely to hide a long parameter list.

Q8: What is a Background?

Background contains context that runs before every scenario in its feature or rule scope. It should be short, relevant, and common to all examples there. Essential differences belong in each scenario, and large repeated setup may be better handled below the Gherkin layer.

Q9: What are Cucumber hooks?

Hooks execute around scenarios and support technical lifecycle work such as starting clients, capturing failure evidence, and cleanup. They can be scoped with tags. I do not hide business preconditions in hooks because readers would lose the context required to understand the rule.

Q10: How do Cucumber tags work?

Tags attach metadata and can be inherited from broader feature structures. Tag expressions select scenarios for execution, such as smoke tests that are not destructive. I document tag ownership and meaning so selection remains predictable in CI.

Q11: Cucumber expressions or regular expressions?

Cucumber expressions provide readable placeholders such as {int}, {string}, and custom parameter types. Regular expressions offer precise matching for specialized patterns. I favor the simpler expression that is unambiguous and centralize domain conversion through custom types.

Q12: How do you share state between steps?

I use a scenario-scoped context or dependency-injection object created for each scenario. Steps read and update only that context. Static fields and global singletons are avoided because they leak data across scenarios and break parallel execution.

Q13: How do you avoid duplicate step definitions?

I maintain a shared domain vocabulary, search existing glue before adding phrases, and organize steps by domain capability rather than feature file. Underlying actions are reusable code. I do not create vague universal steps merely to reduce the step count.

Q14: What causes ambiguous steps?

Ambiguity occurs when more than one step definition matches the same Gherkin step. Broad regular expressions and duplicate domain phrases are common causes. I narrow the expressions, align vocabulary, and remove the duplicate rather than depending on registration order.

Q15: How do you handle undefined steps?

An undefined step has no matching definition. I first confirm the wording belongs in the domain and is not a duplicate variation. Then I implement a thin definition or correct the feature. Undefined steps fail the executable specification and should not be reported as covered behavior.

Q16: How do you run Cucumber scenarios in parallel?

Parallel execution requires scenario-scoped clients, browser contexts, data, files, and reports. Scenarios cannot depend on order or shared mutable records. I configure concurrency through the selected runner and measure environment capacity before increasing workers.

Q17: How do you integrate Cucumber with Selenium or Playwright?

Step definitions call a browser adapter or domain workflow implemented with the chosen library. Browser mechanics and selectors stay below Gherkin. Hooks create and close a scenario-owned browser context, while feature text describes user-visible behavior.

Q18: How do you test APIs with Cucumber?

Steps can call a typed API client to create context, send the event, and store the response. Then steps assert contract and domain outcomes. I use Cucumber where examples help cross-role understanding and ordinary parameterized tests for dense technical combinations.

Q19: What is dry run in Cucumber?

A dry run checks whether Gherkin steps can be matched without executing the underlying test actions. It is useful for detecting undefined or ambiguous glue early. It does not prove that scenarios execute correctly or validate the product.

Q20: How do you rerun failed Cucumber scenarios?

Runner and build-tool integrations can identify failed scenarios for a controlled rerun. I retain the first result and artifacts, distinguish product from infrastructure causes, and never use reruns to calculate an artificially green history. Destructive scenarios require idempotent design before retry.

Q21: How do you write good feature files?

I organize them around capabilities and rules, use consistent domain terms, keep examples concrete, and assert observable outcomes. Scenarios remain short and independent. UI mechanics, incidental data, and automation implementation details stay out unless they are the behavior under test.

Q22: What is the purpose of Rule in Gherkin?

Rule groups scenarios that illustrate one business rule within a feature. It gives readers context and can scope a Background. I use it when it makes the capability's policies easier to navigate, not as an arbitrary folder substitute.

Q23: How do you manage large example datasets?

I keep a small representative set in Gherkin and move exhaustive combinations to lower-level parameterized tests or external governed data when appropriate. Feature reports must stay readable. Every row needs a reason, diagnostic name, independent state, and stable oracle.

Q24: How do you capture screenshots in Cucumber?

An After hook can check scenario failure and attach bytes from the scenario-owned browser or driver. I capture after the failure and before cleanup. Screenshots are paired with logs, traces, request evidence, build identity, and sanitized inputs because an image alone rarely proves root cause.

Q25: How do you organize step-definition files?

I organize glue by domain capability such as orders, accounts, or shipping, not by individual feature file or technical page. Dependencies are scenario-scoped. Shared automation code lives below steps, which prevents one giant file and reduces phrase duplication.

Q26: What is living documentation?

Living documentation is current, accessible behavior documentation connected to executable examples and their results. It stays useful only when teams review wording, remove obsolete cases, and trust execution. A large ignored HTML report is not living documentation.

Q27: How do you measure whether Cucumber is successful?

I look for reduced requirement ambiguity, faster rule decisions, shared vocabulary, useful examples, defect prevention, and trusted execution. Step count and feature count are not success metrics. Maintenance cost and stakeholder readership matter as much as automation output.

Q28: When should you not use Cucumber?

I avoid it when the audience is only developers and plain code communicates better, especially for algorithms, low-level contracts, or dense combinations. I also avoid it when stakeholders will not collaborate on or read the features. The additional language and glue must earn their cost.

Q29: How do you refactor a slow Cucumber suite?

I profile scenario and hook duration, replace UI setup with APIs, move combinatorial rules lower, isolate data, and remove duplicate end-to-end coverage. Feature meaning stays intact. I verify that speed improvements do not discard the observable behavior that made a scenario valuable.

Q30: Design a Cucumber approach for an insurance quote feature.

I would hold example-mapping sessions to identify eligibility, premium, disclosure, and referral rules. Gherkin would document representative boundaries and exclusions. Service tests would cover dense combinations, a few browser scenarios would prove critical journeys, and scenario-scoped data plus clear tags would support reliable CI reporting.

Common Mistakes

  • Describing Cucumber, Gherkin, and BDD as the same thing.
  • Writing feature files after implementation only to mirror test scripts.
  • Encoding clicks, selectors, and page structure in every scenario.
  • Building one scenario that validates many unrelated business rules.
  • Creating vague reusable steps that destroy domain readability.
  • Putting calculations and branching logic inside step definitions.
  • Hiding important business context in hooks.
  • Sharing static state, accounts, or browser sessions between scenarios.
  • Using Scenario Outlines as a home for hundreds of opaque rows.
  • Accumulating tags without documented meaning or owners.
  • Rerunning failures while discarding the first result.
  • Measuring success by the number of feature files rather than shared understanding.

Conclusion

The top Cucumber interview questions test whether you can protect the purpose of executable examples while engineering reliable automation. Separate BDD, Gherkin, Cucumber, and driver code. Write scenarios around rules, keep steps thin, scope state per scenario, use data structures intentionally, and make reports useful to both technical and product readers.

Take one ambiguous requirement and run an example-mapping conversation before writing code. If your final feature clarifies the rule, survives a change of UI technology, and produces actionable CI evidence, you have the foundation for a strong Cucumber interview.

Interview Questions and Answers

What is Cucumber?

Cucumber parses Gherkin feature files, matches steps to executable definitions, runs supporting code, and reports scenarios. It supports executable specifications in a BDD workflow. It does not replace the browser driver, API client, or collaborative practice.

What is BDD?

BDD is a collaborative practice for discovering behavior through concrete examples and a shared domain language. Product, development, and testing perspectives clarify rules and edge cases. Some examples become automated checks, but conversation is the primary mechanism.

What is Gherkin?

Gherkin is a structured language for describing features, rules, examples, context, events, and outcomes. Its keywords make specifications consistent and parseable. Good Gherkin communicates domain behavior instead of low-level automation steps.

What is a step definition?

A step definition binds a Cucumber expression or regular expression to code. It converts parameters and delegates to domain or automation services. Strong definitions are thin, unambiguous, scenario-scoped, and free from duplicated business logic.

Scenario or Scenario Outline?

A Scenario is one concrete example. A Scenario Outline runs the same structure for each Examples row. I use outlines for equivalent variations of one rule and separate scenarios when cases express different rules or need individual names.

What is a DataTable?

A DataTable supplies structured tabular input to a step and can be transformed into lists, maps, or domain objects. It is useful when the representation aids domain reasoning. It should not hide a confusing object graph or an unbounded spreadsheet.

What are Cucumber hooks?

Hooks run around scenarios for technical lifecycle concerns such as creating clients, collecting failure evidence, and cleanup. They can be filtered with tags. Essential business preconditions remain visible in Gherkin instead of being hidden in hooks.

How do Cucumber tags work?

Tags attach metadata to feature structures and tag expressions select scenarios. I use documented concepts such as smoke, destructive, or capability ownership. Tags need governance so CI selection remains stable and understandable.

How do you share state between steps?

A scenario-scoped context or dependency-injection object carries state for one scenario. Static fields and global singletons are prohibited because they leak state across scenarios and workers. Cleanup touches only resources owned by that scenario.

How do you avoid ambiguous Cucumber steps?

I use a consistent vocabulary, prefer precise expressions, and remove duplicate meanings. Broad patterns are narrowed and custom parameter types handle domain conversion. Registration order is not used as a conflict-resolution mechanism.

How do you integrate Cucumber with browser automation?

Step definitions call browser adapters or domain workflows implemented with Playwright, Selenium, or another tool. Locators and timing stay below feature text. A hook creates and closes a scenario-owned browser context, preserving independent execution.

How do you run Cucumber in parallel?

Each scenario receives isolated clients, data, files, and artifacts, with no order dependency. Concurrency is configured through the chosen runner and capped by environment capacity. Reports preserve scenario identity and first-failure evidence.

What is living documentation?

Living documentation is maintained behavior documentation connected to executable examples and current results. Teams must review wording, remove obsolete examples, and make reports accessible. Generated output that nobody trusts or reads does not qualify.

When should you not use Cucumber?

Plain test code can be clearer for algorithms, low-level technical contracts, or dense combinations with no cross-role readership. Cucumber is justified when examples support discovery and lasting shared understanding. The glue and language layer must repay its maintenance cost.

Design Cucumber coverage for insurance quotes.

I would map eligibility, premium, disclosure, and referral rules through collaborative examples. Gherkin would keep representative boundaries and exclusions, service tests would cover dense combinations, and a few UI scenarios would prove critical journeys. Data and clients remain scenario-scoped in CI.

Frequently Asked Questions

What Cucumber topics are commonly asked in interviews?

Common topics include BDD, Gherkin keywords, step definitions, Cucumber expressions, Scenario Outlines, DataTables, Background, hooks, tags, dependency injection, parallel execution, reporting, UI and API integration, and suite design.

Is Cucumber the same as BDD?

No. BDD is a collaborative discovery and delivery practice. Cucumber is a tool that can execute Gherkin examples as part of that practice, but installing Cucumber does not create collaboration or a shared domain language.

How do I write a strong Gherkin scenario?

Describe relevant context, one meaningful event, and observable outcomes using consistent domain language. Keep implementation details out unless the interface behavior itself is the rule, and choose concrete boundary examples.

What language should I use for Cucumber interview preparation?

Use the language required by the role or your strongest production language. Cucumber concepts transfer across JVM, JavaScript, Ruby, and other implementations, while code questions should use APIs supported by that implementation.

How do I prevent duplicate Cucumber steps?

Maintain a shared domain vocabulary, search the glue catalog, and organize steps by capability. Reuse code below the step layer rather than creating broad phrases that can mean anything.

Can Cucumber be used for API testing?

Yes. Step definitions can call API clients for setup, actions, and assertions. Use Cucumber when the examples improve understanding across roles, and use ordinary parameterized tests for dense protocol-level combinations.

When should a team avoid Cucumber?

Avoid it when plain code communicates better, stakeholders will not collaborate on the examples, or the subject is highly technical and combinatorial. The additional Gherkin and glue layer must provide lasting documentation or discovery value.

Related Guides