Top Mostly Asked Cucumber Interview Questions With Code Examples

Here is the list of Top Mostly Asked Cucumber Interview Questions With Code Examples.

What is Cucumber and what are its key features?

Answer: Cucumber is a testing framework that supports Behavior Driven Development (BDD). Its key features include plain English-like syntax, automated tests, and the ability to bridge the gap between technical and non-technical team members.

For More Details
Cucumber Overview: Overview of Java and Cucumber
BDD: BDD | Pros | Cons | Tools | Automation | 3 Amigos

What is the difference between Cucumber Scenario Outline and Examples?

Answer: A Scenario Outline is a template for a scenario with placeholders, while Examples provide concrete values for those placeholders, allowing the scenario to be executed with different sets of data.

Example:

Scenario Outline: Login with different users
  Given I am on the login page
  When I enter "<username>" and "<password>"
  Then I should be logged in

  Examples:
    | username  | password |
    | user1     | pass123  |
    | user2     | pass456  |

What is a Step Definition in Cucumber?

Answer: A Step Definition is a piece of code that maps a step in a feature file to an executable action. It defines the actual implementation of the steps described in the feature files.

Example:

@Given("^I am on the login page$")
public void goToLoginPage() {
   // Code to navigate to the login page
}

What is the purpose of Hooks in Cucumber?

Answer: Hooks in Cucumber allow the execution of pre-defined code blocks before or after specific scenarios or steps. They can be used for setup and teardown operations, such as opening/closing a browser or initializing test data.

Cucumber Hooks: Understanding Cucumber Hooks: Enhancing Automated Testing with Effective Event Handling

Example:

@Before
public void setUp() {
   // Code to set up the test environment
}

@After
public void tearDown() {
   // Code to clean up the test environment
}

What is the difference between Background and Scenario Outline in Cucumber?

Answer: Background is used to define a common set of steps that are executed before every scenario in a feature file. Scenario Outline is used to define a template for scenarios that need to be executed with different sets of data.

Example:

Background:
  Given I am on the login page

Scenario Outline: Login with different users
  When I enter "<username>" and "<password>"
  Then I should be logged in

  Examples:
    | username  | password |
    | user1     | pass123  |
    | user2     | pass456  |

How can you pass data from feature files to Step Definitions in Cucumber?

Answer: Data can be passed from feature files to Step Definitions in Cucumber using placeholders (e.g., <placeholder>) in the steps of Scenario Outline or Examples. These placeholders are then matched with corresponding parameters in the Step Definitions.

Example:

Scenario Outline: Add two numbers
  Given I have entered "<num1>" into the calculator
  And I have entered "<num2>" into the calculator
  When I press add
  Then the result should be "<result>" on the screen

  Examples:
    | num1 | num2 | result |
    | 10   | 20   | 30     |
    | 5    | 15   | 20     |
@Given("^I have entered \"([^\"]*)\" into the calculator$")
public void enterNumber(String number) {
   // Code to enter number into the calculator
}

@When("^I press add$")
public void pressAdd() {
   // Code to perform addition operation
}

@Then("^the result should be \"([^\"]*)\" on the screen$")
public void verifyResult(String expectedResult) {
   // Code to verify the expected result
}

What is the purpose of Tags in Cucumber?

Answer: Tags in Cucumber are used to categorize and filter scenarios. They allow you to selectively execute specific scenarios or groups of scenarios based on the tags assigned to them.

Example

@smoke
Scenario: Login with valid credentials
  Given I am on the login page
  When I enter valid username and password
  Then I should be logged in successfully

@regression
Scenario: Add product to cart
  Given I am on the homepage
  When I add a product to the cart
  Then the product should be added successfully

Explain the difference between Cucumber Expressions and Regular Expressions.

Answer: Cucumber Expressions are a simpler and more user-friendly alternative to Regular Expressions. They provide a way to map natural language phrases to step definitions without the need for complex regex patterns.

Example:

In the above example, the Cucumber Expression {int} will match any positive integer and pass it as a parameter to the step definition.

@Given("I have {int} cucumbers in my basket")
public void cucumbersInBasket(int count) {
   // Code to handle cucumbers in basket
}

How can you skip or ignore a specific scenario in Cucumber?

Answer: To skip or ignore a specific scenario in Cucumber, you can add the @ignore tag to that scenario. Cucumber will exclude any scenario with this tag from the test execution. You need to use ~@ignore along with other tags you want to execute.

Example:

@ignore
Scenario: This scenario will be skipped
  Given some preconditions
  When some actions are performed
  Then some expected results are obtained

What is the purpose of the Cucumber’s Background keyword?

Answer: The Background keyword in Cucumber is used to define a set of common steps that are executed before each scenario in a feature file. It eliminates the need to repeat those steps in every scenario.

Example:

Background:
  Given I am on the login page
  And I have entered valid username and password

Scenario: Add product to cart
  When I add a product to the cart
  Then the product should be added successfully

Scenario: Logout from the application
  When I click on the logout button
  Then I should be logged out successfully

In the above example, the steps defined in the Background section will be executed before both the “Add product to cart” and “Logout from the application” scenarios.

What is the difference between Scenario and Scenario Outline in Cucumber?

Answer: A Scenario represents a specific test case or scenario with concrete steps and expected outcomes. A Scenario Outline, on the other hand, is a template for scenarios that need to be executed with different sets of data.

Example:

Scenario: Login with valid credentials
  Given I am on the login page
  When I enter valid username and password
  Then I should be logged in successfully

Scenario Outline: Add product to cart
  Given I am on the homepage
  When I add "<product>" to the cart
  Then the "<product>" should be added successfully

  Examples:
    | product    |
    | iPhone      |
    | MacBook |

In the above example, the Scenario “Login with valid credentials” is a specific test case, while the Scenario Outline “Add product to cart” is a template that will be executed with different products.

How do you handle dynamic data in Cucumber scenarios?

Answer: To handle dynamic data in Cucumber scenarios, you can use scenario context or scenario outline examples to pass the data between steps. You can also use scenario-level hooks to set up or modify data dynamically before each scenario.

Example:

public class MyScenarioContext {
    private Map<String, Object> scenarioData = new HashMap<>();

    public void setContext(String key, Object value) {
        scenarioData.put(key, value);
    }

    public Object getContext(String key) {
        return scenarioData.get(key);
    }
}

public class MyStepDefinitions {
    private MyScenarioContext scenarioContext;

    public MyStepDefinitions(MyScenarioContext scenarioContext) {
        this.scenarioContext = scenarioContext;
    }

    @Given("I have {int} cucumbers")
    public void iHaveCucumbers(int count) {
        scenarioContext.setContext("cucumberCount", count);
    }

    @When("I eat {int} cucumbers")
    public void iEatCucumbers(int count) {
        int currentCount = (int) scenarioContext.getContext("cucumberCount");
        int remainingCount = currentCount - count;
        scenarioContext.setContext("cucumberCount", remainingCount);
    }

    @Then("I should have {int} cucumbers")
    public void iShouldHaveCucumbers(int count) {
        int currentCount = (int) scenarioContext.getContext("cucumberCount");
        Assert.assertEquals(count, currentCount);
    }
}

In the above example, the scenario context (MyScenarioContext) is used to store and retrieve the dynamic data (cucumberCount) between steps.

Here you can read complete step by step framework creation using cucumber. In this blog, you can see how data is being shared among the steps.

How can you share common step definitions across multiple feature files in Cucumber?

Answer: To share common step definitions across multiple feature files in Cucumber, you can use the glue option in the Cucumber Runner configuration. The glue option allows you to specify the package or class where the step definitions are located.

Example:

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "com.example.stepdefinitions"
)
public class CucumberRunner {
    // Runner configuration
}

In the above example, the step definitions located in the com.example.stepdefinitions package will be shared across all feature files present in the src/test/resources/features directory.

How can you run specific scenarios or tags in Cucumber?

Answer: To run specific scenarios or tags in Cucumber, you can use the --tags option with the Cucumber command-line interface (CLI). The --tags option allows you to specify the tags of the scenarios that you want to execute.

Example:

cucumber --tags @smoke

The above command will execute only the scenarios tagged with @smoke.

How can you handle timeouts in Cucumber scenarios?

Answer: To handle timeouts in Cucumber scenarios, you can use the Timeout option available in the Cucumber Runner configuration. The Timeout option allows you to specify the maximum time duration for a step or scenario to complete. If a step or scenario exceeds the specified timeout, it will fail.

Example:

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "com.example.stepdefinitions",
    monochrome = true,
    snippets = SnippetType.CAMELCASE,
    plugin = {"pretty", "html:target/cucumber-reports"},
    strict = true,
    timeout = 5000 // Timeout set to 5 seconds
)
public class CucumberRunner {
    // Runner configuration
}

In the above example, the timeout for each step or scenario is set to 5 seconds (5000 milliseconds).

How can you handle data-driven testing in Cucumber?

Answer: To handle data-driven testing in Cucumber, you can use the Scenario Outline feature along with Examples. The Examples table allows you to provide different sets of data for the same scenario, and Cucumber will execute the scenario for each set of data.

Example:

Scenario Outline: Add two numbers
  Given I have entered "<num1>" into the calculator
  And I have entered "<num2>" into the calculator
  When I press add
  Then the result should be "<result>" on the screen

  Examples:
    | num1 | num2 | result |
    | 2    | 3    | 5      |
    | 5    | 7    | 12     |

In the above example, the scenario “Add two numbers” is executed twice with different sets of data, resulting in two separate test runs.

How can you generate reports in Cucumber?

Answer: Cucumber provides various reporting plugins to generate reports in different formats, such as HTML, JSON, and XML. You can configure the reporting plugin in the Cucumber Runner configuration.

Example:

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "com.example.stepdefinitions",
    plugin = {"pretty", "html:target/cucumber-reports", "json:target/cucumber-report.json"}
)
public class CucumberRunner {
    // Runner configuration
}

In the above example, the Cucumber runner is configured to generate both HTML and JSON reports. The HTML report is generated in the target/cucumber-reports directory and the JSON report is generated in the target/cucumber-report.json file.

How can you parameterize test data in Cucumber?

Answer: To parameterize test data in Cucumber, you can use scenario outline examples or external data sources such as Excel or CSV files. Scenario outline examples allow you to provide different sets of test data within the feature file itself, while external data sources provide a way to retrieve test data from external files.

Example (Scenario Outline Examples):

Scenario Outline: Add two numbers
  Given I have entered "<num1>" into the calculator
  And I have entered "<num2>" into the calculator
  When I press add
  Then the result should be "<result>" on the screen

  Examples:
    | num1 | num2 | result |
    | 2    | 3    | 5      |
    | 5    | 7    | 12     |

Example (External Data Source – Excel):

public class ExcelUtils {
    public static Object[][] getTestData(String filePath, String sheetName) {
        // Code to read test data from Excel file
    }
}

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "com.example.stepdefinitions",
    plugin = {"pretty"}
)
public class CucumberRunner {
    // Runner configuration

    @BeforeClass
    public static void setUp() {
        String filePath = "path/to/testdata.xlsx";
        String sheetName = "TestData";
        Object[][] testData = ExcelUtils.getTestData(filePath, sheetName);
        // Set test data in a shared context for step definitions to access
    }
}

In the above examples, the first example uses scenario outline examples to provide different sets of test data. The second example demonstrates the usage of an external data source (Excel) to retrieve test data, where a custom utility class (ExcelUtils) is used to read data from the Excel file.

Can you use Cucumber with other testing frameworks?

Answer: Yes, Cucumber can be used with other testing frameworks such as JUnit, TestNG, and Selenium. Cucumber acts as a test runner that executes the feature files and maps the steps to corresponding step definitions written using the chosen testing framework.

Example (Using Cucumber with JUnit)

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "com.example.stepdefinitions",
    plugin = {"pretty"}
)
public class CucumberRunner {
    // Runner configuration
}

In the above example, Cucumber is used with JUnit as the test runner. The @RunWith(Cucumber.class) annotation specifies that JUnit should use Cucumber as the test runner, and the @CucumberOptions annotation is used to configure Cucumber’s behaviour.

Conclusion

These were the cucumber interview questions with answers and code examples. Please let me know if you would like more questions or if there’s anything else I can assist you with!

Please feel free to send your cucumber interview questions to us.

Leave a Comment