0
votes

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

1
Use DI with constructor injection in the step definition classes by using the cucumber picocontainer. For a scenario the DI container will inject the same instance of the object. Also why are u passing the testrunner to the step definition class? - Grasshopper
@Grasshopper , Thanks. I didnt know about the pico-container. Scenarios are working fine now - Akash Singh
About the testrunner, My WebDriverManager is not completed so I am fetching the driver instance straight from the TestRunner class by a method. Not a good way but I look forward to rectifying that soon - Akash Singh
Google ThreadLocal to store the driver instance specific to a thread. Ideal for parallel running too. - Grasshopper

1 Answers

0
votes

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

Just add the dependency:

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
    <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