artofcode.info

The beauty of coding!

Generic Scenario Context for Cucumber

Author Avatar steti 19 Oct 2020
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

It allows you to share data of any type between steps without explicit casting, making your step definitions cleaner and less coupled.

How to Cite This Article

APA Format: steti. (2020). Generic Scenario Context for Cucumber. Retrieved from https://artofcode.info/posts/generic-scenario-context-for-cucumber
MLA Format: steti. "Generic Scenario Context for Cucumber." Steti.info, 19 Oct 2020. https://artofcode.info/posts/generic-scenario-context-for-cucumber
Chicago Format: steti. "Generic Scenario Context for Cucumber." Steti.info. October 19, 2020. https://artofcode.info/posts/generic-scenario-context-for-cucumber
Back to Posts