Generic Scenario Context for Cucumber

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 {


Step 4: Use it in your steps

For saving data:, 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.