← Back to Blog

October 19, 2020 · 5 views

Generic Scenario Context for Cucumber

Testing Automation
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 {
    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.

Frequently Asked Questions

What is the purpose of a Scenario Context in Cucumber?

A Scenario Context is used to share state and data between different steps in a Cucumber scenario, allowing you to pass information (like created IDs or response data) from one step to another without using global variables.

📚 How to Cite This Article

APA Format:

I enjoy building things that live on the internet. (2020). Generic Scenario Context for Cucumber. Steti.info. https://steti.info/blog/generic-scenario-context-for-cucumber

MLA Format:

I enjoy building things that live on the internet. "Generic Scenario Context for Cucumber." Steti.info, 19 Oct. 2020. https://steti.info/blog/generic-scenario-context-for-cucumber.

Chicago Style:

I enjoy building things that live on the internet. "Generic Scenario Context for Cucumber." Steti.info. October 19, 2020. https://steti.info/blog/generic-scenario-context-for-cucumber.

Published: October 19, 2020
Last Updated: November 29, 2025

About the Author

Author
I like to build from websites to web apps, I create digital experiences that solve real problems and delight users and the most important is that all that I build, I build with PEOPLE!
Learn more about the author →

Related Posts