How to Share same selenium Driver between step definitions
I had the chance to work in couple of Java automation environments and I always tried to improve the way selenium is used and properly share same selenium Driver between step definitions.
Imagine you have a Java Selenium project with Cucumber jvm to run your functional tests against your app. And the whole idea of a page object pattern is to create our testing code maintainable, reusable and Page Factory is an optimized way to create object repository in POM concept
Using Selenium webdriver you’ll have to share the driver instance between your step definitions. Imagine a feature file that defines couple of steps: one to navigate to a page, another to click on an element and another to assert something. If all steps happen to be defined in separate files, the first step definition will use its driver to navigate to the page. By the time the second step definition runs the click action its driver it hasn’t navigated to the page (since those actions went to the other driver) and the test fails.
Using pico-container as a dependency you can share same selenium Driver between step definitions.
Assuming you have a BrowserFactory that looks something like this:
A very slightly modified version of SharedDriver from cucumber-jvm :
And now our PicoDependencyInjector class :
So here we use pico-container as a dependency injection framework to use with
And our Page class and Step definitions class will look something like this :
Step definition class:
Maven dependency :
We will cover in a different topic how to build a project with cucumber jvm from scratch , till then hope this will help.