Skip to content

artofcode.info

The beauty of coding!

Menu
  • Home
  • Front-End
    • Angular
    • Javascript
    • ReactJS
  • Back-End
    • Java
    • Php
  • Test Automation
  • News
Menu
SHARE-DATA-BETWEEN-STEPS-IN-CUCUMBER-USING-SCENARIO-CONTEXT

Generic Scenario Context for Cucumber

Posted on October 19, 2020October 19, 2020 by guru

How to Share Test Context between Cucumber Steps, in this post we will explain it and share our implementation

Scenario Context class holds the test data information explicitly. It helps you store values in a key-value pair between the steps. Moreover, it helps in organizing step definitions better rather than using private variables in step definition classes.

We are going to implement the Scenario Context in cucumber for sharing data between our Step Definitions in a generic way.

 

Step 1: Create a Scenario Context class

    private static final Map<ScenarioKeys, Object> data = new HashMap<>();

    public void save(ScenarioKeys scenarioKeys, Object value) {
        data.put(scenarioKeys, value);
    }

    public <T> T getData(ScenarioKeys scenarioKeys) {
        return (T) data.get(scenarioKeys);
    }
}

 

Step 2: Create an Interface that will be implemented by enum

public interface ScenarioKeys {
}

 

Step 3: Implement ScenarioKeys  by an enum for type-safe

 

public enum PageScenarioKeys implements ScenarioKeys {
    CURRENT_PAGE;

 

Step 4: Use it in your steps

For saving data:

 scenarioContext.save(PageScenarioKeys.CURRENT_PAGE, object); 

For getting data:

AbstractPageObject currentPage = scenarioContext.getData(PageScenarioKeys.CURRENT_PAGE);

Because we are returning a generic type <T> then we are getting data from HashMap we don’t need to cast it in step implementation and another advantage is that we can save any type of data in our scenario context that why this is a generic way to use a scenario context for sharing data between scenarios and steps.

Recent Posts

  • Cucumber JUnit XML report with logs
  • How to add log messages to the cucumber Jenkins report
  • Factory Method Pattern in the creation of Selenium WebDriver
  • How to attach log message to cucumber report via MDC
  • How to send different values in cucumber features based on profile
  • How to log execution time for cucumber steps
  • Strategy Pattern in Test Automation with Selenium WebDriver
  • Spring Security with JWT token

Categories

  • Back-End
  • Java
  • News
  • Test Automation
© 2023 artofcode.info | Powered by Minimalist Blog WordPress Theme