</>

Technology

Cucumber

Difficulty

Beginner

Interview Question

What is the purpose of the Examples keyword in Cucumber?

Answer

Examples Keyword in Cucumber

Purpose

Examples keyword is used to supply test data to a Scenario Outline. Every row in the Examples table results in one execution of the scenario with that row's values substituted into the <placeholder> tokens.

Rules

  1. Examples must follow Scenario Outline — it cannot be used with regular Scenario
  2. First row is the header (column names = placeholder names)
  3. Each subsequent row is one test execution
  4. Column names must exactly match the <placeholders> in the scenario

Syntax

Gherkin
Scenario Outline: Verify product prices
  Given the user is on the product catalog page
  When the user searches for "<product>"
  Then the price displayed should be "<price>"
  And the availability should be "<availability>"

  Examples:
    | product  | price  | availability |
    | Laptop   | $999   | In Stock     |
    | Phone    | $599   | In Stock     |
    | Tablet   | $399   | Out of Stock |
    | Watch    | $199   | In Stock     |

This runs 4 tests — one for each data row.

Multiple Examples Blocks

You can have multiple Examples sections with tags:

Gherkin
Scenario Outline: Login test
  When the user logs in as "<username>"
  Then the result should be "<outcome>"

  @smoke
  Examples: Valid Users
    | username | outcome   |
    | admin    | Dashboard |
    | user     | Home      |

  @negative
  Examples: Invalid Users
    | username  | outcome              |
    | hacker    | Access Denied        |
    | unknown   | User not found       |

In Step Definitions

Parameters from Examples are passed as method arguments in the same order they appear in the step:

Java
@When("the user searches for {string}")
public void searchProduct(String product) {
    // Called once per Examples row with that row's value
    searchBox.sendKeys(product);
}

@Then("the price displayed should be {string}")
public void verifyPrice(String expectedPrice) {
    assertEquals(expectedPrice, priceElement.getText());
}

Follow AutomateQA

Related Topics