What is Scenario Outline in Cucumber

  

What is Scenario Outline in Cucumber?

Scenario Outline in Cucumber is used when you want to run the same scenario multiple times with different sets of data. This is extremely useful for data-driven testing.

It avoids repeating the same scenario logic and makes the feature file clean, readable, and maintainable.


Why Use Scenario Outline?

  • To avoid writing multiple similar scenarios.

  • To test the same logic with different data inputs.

  • To improve test coverage.


How It Works

  • Scenario Outline is written like a normal scenario.
  • Examples keyword is used to provide the input data in a tabular format.
  • Each row in the Examples table is treated as a new execution of the scenario.
  • The placeholders (example: <username><password>) are replaced with values from the Examples table during execution.



Syntax of Scenario Outline

Scenario Outline: Scenario title
  Given some step with <parameter1>
  When action with <parameter2>
  Then expected result

Examples:
  | parameter1 | parameter2 |
  | value1     | value2     |
  | value3     | value4     |



Example: Login Functionality

Feature File: login.feature


Feature: Login Feature

  Scenario Outline: Valid login with different users
    Given User is on Login page
    When User enters username "<username>" and password "<password>"
    Then Login should be successful

    Examples:
      | username | password  |
      | user1    | pass123   |
      | user2    | pass456   |
      | admin    | admin@123 |




Step Definition File (Java)

package stepdefinitions;

import io.cucumber.java.en.*;

public class LoginSteps {

    @Given("User is on Login page")
    public void user_is_on_login_page() {
        System.out.println("User is on Login page");
    }

    @When("User enters username {string} and password {string}")
    public void user_enters_credentials(String username, String password) {
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
    }

    @Then("Login should be successful")
    public void login_should_be_successful() {
        System.out.println("Login successful!");
    }
}


How It Runs

Cucumber will run the scenario 3 times, once for each row in the Examples table:

  • user1 / pass123
  • user2 / pass456
  • admin / admin@123


Benefits of Scenario Outline

  • Reusability of test steps.

  • Better test coverage for multiple inputs.

  • Easy to maintain and extend.

What is Scenario in Cucumber

 

What is a Scenario in Cucumber?

Scenario in Cucumber is a concrete example that illustrates a business rule or requirement. It is written in Gherkin language, which is designed to be easily understandable by non-technical stakeholders such as business analysts and testers.

Each scenario represents a single test case that describes a specific functionality or behavior of the system under test, using the Given-When-Then structure.


Gherkin Keywords used in Scenario

  • Given: Describes the initial context or state of the system.

  • When: Specifies the action or event performed by the user.

  • Then: Describes the expected outcome or result.

  • AndBut: Used to add more steps for clarity.



Example: Scenario in Cucumber

Feature File - Login.feature



Feature: Login functionality for a web application

  Scenario: Successful login with valid credentials
    Given User is on the login page
    When User enters valid username and password
    And clicks on the login button
    Then User should be redirected to the home page





Step Definition File - LoginStepDefinitions.java

package stepDefinitions;

import io.cucumber.java.en.*;

public class LoginStepDefinitions {

    @Given("User is on the login page")
    public void user_is_on_login_page() {
        System.out.println("Navigated to login page");
        // You can use Selenium code like: driver.get("http://example.com/login");
    }

    @When("User enters valid username and password")
    public void user_enters_credentials() {
        System.out.println("Entered username and password");
        // Selenium code to enter username and password
    }

    @When("clicks on the login button")
    public void user_clicks_login() {
        System.out.println("Clicked login button");
        // Selenium code to click login button
    }

    @Then("User should be redirected to the home page")
    public void user_redirected_home() {
        System.out.println("User is on the home page");
        // Selenium code to verify redirection
    }
}





Test Runner File - TestRunner.java

package runners;

import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "stepDefinitions"
)
public class TestRunner {
}





Important Points:

TermDescription
ScenarioA single test case describing a user story or feature behavior
Feature FileContains one or more scenarios
Step DefinitionsJava methods mapped to each Gherkin step
Runner ClassExecutes the scenarios with JUnit or TestNG

Data Table in Cucumber

  

What are Data Tables in Cucumber?

In CucumberData Tables are used to pass structured data (like tabular format) to steps in a feature file. It allows you to supply multiple rows of input to a single step in a Gherkin scenario.

They are especially useful when you want to test a scenario using multiple sets of values for the same action without repeating the entire scenario.


Why Use Data Tables?

  • Makes test cases more readable and maintainable.

  • Allows passing multiple sets of data (rows and columns).

  • Avoids duplication of steps.

  • Makes your tests data-driven.




Types of Data Tables in Cucumber
  • One-Dimensional Data Table – like a list.
  • Two-Dimensional Data Table – like a table with headers.
  • Without Header – multiple rows but no column names.


1. Feature File with Data Table

Feature: Login Feature

  Scenario: Successful login with valid credentials
    Given the user enters the following credentials
      | username | password  |
      | john123  | pass123   |


 

2. Step Definition for Data Table (Java)

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

public class LoginSteps {

    @Given("the user enters the following credentials")
    public void the_user_enters_the_following_credentials(DataTable dataTable) {
        List<Map<String, String>> credentials = dataTable.asMaps(String.class, String.class);

        for (Map<String, String> credential : credentials) {
            String username = credential.get("username");
            String password = credential.get("password");
            System.out.println("Username: " + username + ", Password: " + password);

            // Here you can call your login method or perform UI action
            // loginPage.login(username, password);
        }
    }
}


How it Works

  • DataTable is automatically passed to your step definition.

  • asMaps(String.class, String.class) converts each row into a Map where:

    • Key = column header

    • Value = cell value


You can use Data Tables in scenarios like:

  • Filling forms with multiple values

  • Testing multiple login credentials

  • Verifying entries in a shopping cart




Important Points:

FeatureDescription
Data TableStructured input passed to steps
FormatTabular (rows and columns)
ConversionUse .asList() or .asMaps()
Use CasesData-driven testing, repeated data input

Maps in Data Tables in Cucumber

  

In Cucumber, a Data Table can be converted into a Map when the data is represented as a single row with two columns (Key-Value pair). This is useful when you want to pass configuration data or form field values to a step definition in a structured way.


What is a Map in Data Table?

Map in a data table is a key-value pair where the first column is considered the key, and the second column is the value.



Format Example:

Feature: Login Feature

  Scenario: Successful login with valid credentials
    Given the user logs in with the following details
      | username | testuser |
      | password | testpass |



Step Definition (Java):

You can access this data as a Map<String, String> using DataTable.asMap().

hilite.me-->
import io.cucumber.java.en.Given;
import io.cucumber.datatable.DataTable;

import java.util.Map;

public class LoginStepDef {

    @Given("the user logs in with the following details")
    public void user_logs_in_with_details(DataTable dataTable) {
        Map<String, String> loginDetails = dataTable.asMap(String.class, String.class);
        
        String username = loginDetails.get("username");
        String password = loginDetails.get("password");

        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        
        // Add login logic here
    }
}


Explanation:

  • DataTable is converted to Map<String, String> using .asMap(String.classString.class)

  • Each row in the table becomes a key-value pair in the map.

  • Very useful for form inputs or structured key-value data.



Output

Username: testuser
Password: testpass

Tags in Cucumber

  

Tags in Cucumber are used to filter scenarios or features for execution. They are written using the @ symbol and help organize or group test cases.


You can:

  • Run only specific scenarios.

  • Skip specific scenarios.

  • Group scenarios for smoke, regression, sanity testing, etc.



Why Use Tags?

  • To control which scenarios to run.

  • To categorize tests like @smoke@regression@login, etc.

  • To exclude certain tests during a test run.



Example Feature File with Tags (Login.feature)

@regression
Feature: Login functionality

  @smoke @login
  Scenario: Successful login
    Given the user is on the login page
    When the user enters valid credentials
    Then the user should be redirected to the home page

  @negative
  Scenario: Login with invalid credentials
    Given the user is on the login page
    When the user enters invalid credentials
    Then an error message should be displayed


How to Run Scenarios with Tags?

When using JUnit with Cucumber, configure the @CucumberOptions in the test runner class.



Test Runner Class Example:

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "stepdefinitions",
    tags = "@smoke",
    plugin = {"pretty", "html:target/cucumber-reports"}
)
public class TestRunner {
}


tags Options:

ExpressionDescription
@smokeRuns scenarios with @smoke tag
@smoke and @loginRuns scenarios with both tags
@smoke or @regressionRuns scenarios with either tag
not @negativeExcludes scenarios with @negative tag


Important Points:

  • Tags can be placed above Feature or Scenario.

  • Tags can be combined using logical operators (andornot).

  • Cucumber treats tags case-sensitive.

Tagged Hooks in Cucumber

  

What are Tagged Hooks in Cucumber?

Tagged Hooks in Cucumber are special types of hooks (@Before, @After) that run only for scenarios with specific tags. This allows for fine-grained control over the setup and teardown of tests based on the tags assigned to scenarios or features.

Instead of running a hook before/after every scenario (as general hooks do), tagged hooks run only when the tag matches.


Why Use Tagged Hooks?

  • Run different setup/teardown for different scenario groups (like @Smoke@Regression, etc.)

  • Optimize test execution time

  • Avoid unnecessary setup for unrelated tests



Syntax of Tagged Hooks

@Before("@Smoke")
public void beforeSmokeTests() {
    // Code to run before scenarios tagged with @Smoke
}

@After("@Regression")
public void afterRegressionTests() {
    // Code to run after scenarios tagged with @Regression
}


Example Code

Feature File – login.feature

@Smoke
Feature: Login Feature

  @Smoke
  Scenario: Valid Login
    Given User is on login page
    When User enters valid credentials
    Then User should be navigated to the homepage

  @Regression
  Scenario: Invalid Login
    Given User is on login page
    When User enters invalid credentials
    Then User should see an error message




Step Definition Class – LoginSteps.java

package stepDefinitions;

import io.cucumber.java.en.*;

public class LoginSteps {

    @Given("User is on login page")
    public void user_is_on_login_page() {
        System.out.println("User navigates to login page");
    }

    @When("User enters valid credentials")
    public void user_enters_valid_credentials() {
        System.out.println("User enters correct username and password");
    }

    @When("User enters invalid credentials")
    public void user_enters_invalid_credentials() {
        System.out.println("User enters wrong username and password");
    }

    @Then("User should be navigated to the homepage")
    public void user_should_be_navigated_to_the_homepage() {
        System.out.println("User is redirected to the homepage");
    }

    @Then("User should see an error message")
    public void user_should_see_an_error_message() {
        System.out.println("Error message is displayed");
    }
}




Hooks Class – Hooks.java

package stepDefinitions;

import io.cucumber.java.Before;
import io.cucumber.java.After;

public class Hooks {

    @Before("@Smoke")
    public void setupForSmoke() {
        System.out.println("Setting up SMOKE environment...");
    }

    @After("@Smoke")
    public void tearDownForSmoke() {
        System.out.println("Tearing down SMOKE environment...");
    }

    @Before("@Regression")
    public void setupForRegression() {
        System.out.println("Setting up REGRESSION environment...");
    }

    @After("@Regression")
    public void tearDownForRegression() {
        System.out.println("Tearing down REGRESSION environment...");
    }
}


Output When Running Scenarios

If you run the @Smoke scenario, output will be:

Setting up SMOKE environment...
User navigates to login page
User enters correct username and password
User is redirected to the homepage
Tearing down SMOKE environment...


If you run the @Regression scenario, output will be:

Setting up REGRESSION environment...
User navigates to login page
User enters wrong username and password
Error message is displayed
Tearing down REGRESSION environment...