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