These Cucumber interview questions for freshers cover the first year and a half: what BDD is, Gherkin keywords and feature files, step definitions and runners, Cucumber expressions, then hooks, tags, data tables, page objects and sharing state between step classes.

Cucumber interview questions by experience: Freshers · 3 years · 5 years

Fresher Questions: BDD, Gherkin and Cucumber Basics

What is BDD?

BDD (Behaviour-Driven Development) is a software development approach where test scenarios are written in plain English using the Given-When-Then format before development begins. It bridges the gap between business and technical teams by using a common language everyone understands. Tools: Cucumber (Java), SpecFlow (.NET), Behave (Python).

What is Cucumber?

Cucumber is a BDD testing framework that reads Gherkin-formatted feature files and executes the corresponding Java step definitions. It supports multiple languages (Java, Ruby, JavaScript, Python) and integrates with Selenium, REST Assured, Appium, and CI/CD pipelines.

What is Gherkin?

Gherkin is the plain-English language used to write BDD test scenarios. It uses keywords: Feature, Background, Scenario, Scenario Outline, Given, When, Then, And, But, Examples, and @ tags. It is stored in .feature files and is the bridge between human-readable requirements and automated test code.

What is a Feature file?

A .feature file contains one Feature and one or more Scenarios written in Gherkin. It lives in src/test/resources/features. It describes the desired behaviour of a feature from a user's perspective. Each line starting with Given, When, Then, And, But maps to a Java step definition method.

What is the Given-When-Then format?

Given: describes the precondition or initial context (system state before the action). When: describes the action or event being tested (what the user does). Then: describes the expected outcome (what should happen). Example: Given I am on the login page / When I enter valid credentials / Then I should see the dashboard.

What is a Step Definition?

A Java method annotated with @Given, @When, @Then, @And, or @But that contains the automation code corresponding to a Gherkin step. Cucumber matches the step's text to the annotation's expression using regex or Cucumber Expressions and calls the method. All step definitions must be in the package specified in the glue option.

What is @CucumberOptions?

@CucumberOptions is an annotation on the TestRunner class that configures how Cucumber runs. Key parameters: features (path to .feature files), glue (package with step defs and hooks), tags (filter scenarios), plugin (report formats), monochrome (clean output), dryRun (validate bindings without running).

What is the glue option in @CucumberOptions?

The glue option specifies the Java package(s) where Cucumber should look for step definitions and hooks. If your steps are in stepdefs package and hooks in hooks package, use: glue = {"stepdefs", "hooks"}. Cucumber scans all classes in those packages for @Given/@When/@Then/@Before/@After methods.

What is the difference between Scenario and Scenario Outline?

Scenario: a single test case with fixed data in the steps. Scenario Outline: a template that runs the same scenario multiple times with different data from an Examples table. Variables are wrapped in <angle brackets> in the steps and matched to column headers in the Examples table.

What is the Examples table in Cucumber?

The Examples table provides the data for a Scenario Outline. It has a header row with column names and one or more data rows. Each row triggers one execution of the scenario with the column values substituted for the <placeholders> in the step text. Example: | username | password | then steps use <username> and <password>.

What is the Background keyword?

Background contains steps that run before EVERY scenario in the feature file. It avoids repeating common setup steps (like opening a browser or navigating to a page). Background is executed once per scenario, not once per feature file. It appears after the Feature line and before the first Scenario.

What is the difference between And and But?

And and But are syntactic aliases for the previous step type. If the previous step was Given, And acts as Given. If it was When, And acts as When. But is used for negative conditions: Then I should see the dashboard / But I should not see any errors. They improve readability without changing behaviour.

What is dryRun in @CucumberOptions?

dryRun=true validates that every Gherkin step has a matching step definition without actually executing the test code. It checks for undefined or ambiguous steps. Useful when you write feature files first and want to verify all bindings before running the full suite. In v7, the default is false.

What is the Cucumber Expression {string}?

In Cucumber Expressions, {string} matches any text surrounded by single or double quotes in the Gherkin step and passes it as a String parameter to the step definition method. Example: When I enter username "admin" — the step @When("I enter username {string}") receives "admin" as the String argument.

What is monochrome in @CucumberOptions?

monochrome=true removes ANSI escape codes from the console output, making it readable in environments that don't support colors (like CI/CD logs). Without it, the output contains unreadable characters on Windows or plain-text log viewers. Always set to true in your runner.

What are Cucumber plugins (reporters)?

Plugins define how Cucumber generates output. Common ones: pretty (formatted console output), html (HTML report file), json (JSON data file used by third-party reporting tools), junit (XML format for CI integration), rerun (writes failed scenario locations for re-run). Specify multiple in the plugin array.

What is the difference between @CucumberOptions tags and feature-level tags?

@CucumberOptions tags filter which scenarios RUN. Feature-file tags (@ symbol) label scenarios for organisation and filtering. A @smoke tag on a scenario means it is part of the smoke suite. In the runner: tags = "@smoke" runs only @smoke scenarios. tags = "@smoke and not @wip" runs smoke but skips WIP.

What is the purpose of the TestRunner class?

TestRunner extends AbstractTestNGCucumberTests (or AbstractJUnit4CucumberRunner) and holds the @CucumberOptions configuration. It is the entry point for Cucumber test execution. Each scenario in the feature files becomes a separate TestNG test method, enabling parallel execution and TestNG reporting.

How does Cucumber match Gherkin steps to Java methods?

Cucumber reads each Gherkin step's text and tries to match it to a step definition annotation using either Cucumber Expressions ({string}, {int}) or regular expressions. If exactly one match is found, that method is called. If no match is found, the step is Undefined. If multiple match, it is Ambiguous (an error).

What is an Undefined step in Cucumber?

An Undefined step has no matching step definition. Cucumber prints the step in yellow in the console and prints a code snippet you can copy to implement the step. The scenario is marked as Undefined (not Failed). Use dryRun=true to find all undefined steps at once before running.

What is a Pending step in Cucumber?

A step that has a step definition but the method throws cucumber.api.PendingException (or is empty with a TODO comment). It marks the scenario as Pending rather than Failed. Used as a placeholder when the step definition file exists but the implementation is not complete yet.

What is the difference between @Before and @BeforeAll in Cucumber?

@Before (io.cucumber.java.Before) runs before EACH scenario — used for browser setup, creating test data. @BeforeAll does not exist natively in Cucumber-JVM; use @BeforeClass in TestNG or JUnit or use a static initialiser. Hooks in Cucumber are scenario-scoped, not class-scoped.

Can you have multiple step definition classes?

Yes. Cucumber scans all classes in the glue package. You can split steps logically: LoginSteps.java, SearchSteps.java, CheckoutSteps.java. Steps from all classes are available to all feature files. Avoid duplicate step definitions across classes — Cucumber will throw an Ambiguous match error.

What is the pretty plugin in Cucumber?

The pretty plugin formats the Cucumber output in the console, showing the feature name, scenario name, and each step with colours — green for passed, red for failed, yellow for undefined. It also prints the step arguments. It is added as: plugin = {"pretty"} in @CucumberOptions.

What is Gherkin's Rule keyword?

Rule (Cucumber v7+) groups related scenarios under a business rule within a Feature. It improves organisation in large feature files. Example: Rule: Admin users can delete accounts. Under each Rule you can have a Background and multiple Scenarios. It does not affect execution — it is organisational only.

Advertisement

Junior Questions: Hooks, Tags, Data Tables and Page Objects

What are Hooks in Cucumber?

Hooks are methods annotated with @Before, @After, @BeforeStep, or @AfterStep that run automatically at specific points in scenario execution. @Before runs before each scenario (browser setup). @After runs after each scenario (teardown, screenshot). They live in a class in the glue package. They are NOT tied to specific feature files.

What is the difference between @Before in JUnit and @Before in Cucumber?

JUnit's @Before runs before each test method in a class. Cucumber's @Before (io.cucumber.java.Before) runs before each Scenario across all feature files. They serve the same purpose but Cucumber hooks apply globally to all scenarios and support tag filters: @Before("@smoke").

How do you take a screenshot on test failure in Cucumber?

In the @After hook, check scenario.isFailed(). If true, cast WebDriver to TakesScreenshot and call getScreenshotAs(OutputType.BYTES). Attach the bytes to the scenario: scenario.attach(screenshot, "image/png", "name"). The screenshot appears in the Cucumber HTML report.

What is the Scenario object in Cucumber hooks?

The Scenario object (io.cucumber.java.Scenario) can be injected into @Before and @After methods. It provides: scenario.getName(), scenario.getId(), scenario.isFailed(), scenario.getStatus(), scenario.getTags(), scenario.attach(bytes, mediaType, name). Used for conditional logic and attaching screenshots to reports.

What is the order of execution in Cucumber?

Feature file is parsed → For each Scenario: @Before hooks (in order) → Background steps → Scenario steps → @After hooks (in reverse order). Background runs per scenario, not per feature. @BeforeAll and @AfterAll can be done with static initializers or JUnit5/TestNG suite-level annotations.

What are tags in Cucumber and how do you use them?

Tags (@ prefix) label Feature files, Scenarios, or Scenario Outlines for filtering and organisation. Set in runner: tags = "@smoke". Tag expressions: @smoke and not @wip, @smoke or @regression. Run from Maven: mvn test -Dcucumber.filter.tags="@smoke". Tags on Feature apply to all scenarios in that file.

What is a Data Table in Cucumber?

A Data Table is a structured multi-column table passed as a parameter within a single scenario step. It does NOT create multiple test runs (unlike Scenario Outline). It is received in the step definition as DataTable, Map<String,String>, List<Map<String,String>>, or List<List<String>> and is used to pass multiple related values.

What is the difference between Data Table and Scenario Outline?

Scenario Outline: creates multiple test executions — one per row in the Examples table. Data Table: passes a table as a single parameter to one step method — no multiple runs. Use Scenario Outline for running the same scenario with different inputs. Use Data Table for passing bulk structured data to one step.

How do you share WebDriver between step definition classes?

Use Dependency Injection with PicoContainer (cucumber-picocontainer). Create a TestContext class holding the WebDriver and page objects. Both step definition classes accept TestContext in their constructor. PicoContainer creates one instance per scenario and injects the same instance into all classes — sharing state.

What is PicoContainer in Cucumber?

PicoContainer is a lightweight Dependency Injection container used by Cucumber. Add cucumber-picocontainer to pom.xml. Cucumber automatically detects constructor injection — if two step def classes both need a TestContext object, PicoContainer creates one instance and injects it into both. No configuration needed.

What is the @Ignore tag in Cucumber?

@wip (work in progress) is a conventional tag, not a Cucumber-specific keyword. To skip scenarios, add a custom tag and exclude it in the runner: tags = "not @wip". Or use the @Ignore annotation if integrated with JUnit. There is no built-in @Ignore in Cucumber — you use tag exclusion.

What is the rerun plugin in Cucumber?

The rerun plugin: plugin = {"rerun:target/rerun.txt"} writes the file paths and line numbers of FAILED scenarios to a text file. A second runner can read this file: features = "@target/rerun.txt" to rerun only failed scenarios. Useful in CI to retry failures without re-running the entire suite.

How do you run only failed scenarios in Cucumber?

Step 1: Add plugin = {"rerun:target/rerun.txt"} to your main runner. Step 2: Create a FailedTestRunner class with features = "@target/rerun.txt" and same glue. Step 3: Run FailedTestRunner to re-execute only the failed scenarios. Used to handle flaky tests or network-related failures.

What is the difference between @Given, @When, @Then, and @And?

Functionally they are identical — any annotation matches any Gherkin step. The distinction is semantic: @Given for preconditions, @When for actions, @Then for assertions. @And and @But are aliases for the previous step type in the feature file. Best practice: annotate methods with the semantically correct keyword for readability.

Can the same step definition be used in multiple feature files?

Yes. Step definitions are global — any step in any feature file that matches a step definition is automatically bound to it. This is by design in Cucumber. It promotes reuse. For example, a step "I click the Login button" can be shared across Login.feature and ForgotPassword.feature.

What is soft assertion vs hard assertion in Cucumber?

Hard assertion (TestNG Assert, JUnit Assertions): fails the step immediately and marks the scenario as failed. Soft assertion (SoftAssert in TestNG, assertAll in JUnit 5): collects all failures and reports them at the end of the scenario. Use soft assertions when you want to check multiple conditions in a Then step without stopping at the first failure.

How do you parameterise browser type in Cucumber?

Store browser type in config.properties (browser=chrome). Read in DriverManager using ConfigReader. Override from command line: mvn test -Dbrowser=firefox. Use a factory pattern in DriverManager: if chrome → ChromeDriver, if firefox → FirefoxDriver. The feature file and step definitions don't change — only configuration changes.

What is the json plugin used for?

plugin = {"json:target/cucumber-reports/report.json"} generates a JSON file with full test result data. This JSON is consumed by third-party reporting tools: ExtentReports (via ExtentCucumberAdapter), Cluecumber, Allure, and Jenkins Cucumber Reports plugin to generate interactive HTML dashboards.

How do you write a step with multiple parameters?

Use multiple Cucumber Expression parameters: @When("I enter {string} and {string}") for two strings, @When("I add {int} items at {double} each") for int and double. They map to method parameters in left-to-right order. For regex: @When("^I enter \"(.+)\" and \"(.+)\"$") maps to two String parameters.

What is the World object in Cucumber?

In Cucumber-JVM, there is no World object (that concept is from Cucumber-Ruby). State sharing in Java is done via Dependency Injection (PicoContainer, Spring, Guice) or static ThreadLocal holders. The equivalent of Ruby's World is a TestContext class injected into step def constructors via PicoContainer.

FAQs

What is the most asked Cucumber question for freshers?

The difference between Scenario and Scenario Outline, and how step definitions are matched to Gherkin steps through Cucumber expressions or regular expressions.