Passing Scenario Context Between Multiple Step Definition Classes

Passing Scenario Context Between Multiple Step Definition Classes

So, I started developing a framework using Cucumber/TestNG/Java/selenium I have a Context class that saves the scenariocontext with the help of enums in the form of key value pair Referenced from here

My issue is that: For a particular scenario in a feature, Step definitions are defined in multiple classes:

Sample feature

Feature: A feature
Scenario: Scenario
Given Statement 1
Then Statement 2

Class1

Class firstDef{
TestRunner test;
public firstDef(TestRunner test){
this.test = test
}
Brain context = new Brain();
@Given("Statement1")
void method1(){
}
}

Class 2

Class secondDef{
TestRunner test;
public secondDef(TestRunner test){
this.test = test
}
Brain context = new Brain();
@Given("Statement2")
void method1(){
}
}

TestRunner class

Class TestRunner{
//some code
@Test
public method1(){
//some code
}
}

So,

The brain class object for every step-definition will be different, this doesn't help as I want the context to be same throughout the scenario

Even if I instantiate the Brain in Runner class, the instance will be new for every instance of the test class

To overcome this, one possible solution that I have thought of is Serialization and de-serialization

In the @BeforeClass method, I will have:

File f = new File(path);
if(!f.exists()){
Brain context = new Brain();
FileOutputStream fos = new FileOutputStream(name);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(context);
}

Then I can deserialize wherever I want the context and serialize again after making changes to same reference variable

Is the above method correct or is there a better way to overcome the same problem

4

1 Answer

Constructor injection with Cucumber PicoContainer works like a charm for the above problem

Just add the dependency:

<!--  -->
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

to your pom.xml(For Maven projects) and pass the HashMap class's reference variable through multiple step definition classes and it will remain the same over a scenario.

Please have a go through this article for detailed explaination

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.