'Create Selenium Webdriver once and use in Cucumber's all steps

I've experience in Back-End automation testing, but I'm new to Front-End. I've created BDD format tests for a website and now I want to automate it. I decided to use Selenium + cucumber using Maven for desktop versions of website.

Now let's start:

For example my feature file looks something like this:

Feature: User change password page
Scenario: User doesn't provide passwords
Given user is logged in 
And user is on change password page
When user clicks SAVE button
Then website should notify that password fields are mandatory

Scenario: User types wrong current password
Given user is logged in 
And user is on change password page
When user provides invalid current password
And user clicks on save button
Then website should notify user that current password is invalid

At first I thought it would be good that I log in the system only for first scenario. (in this example in second scenario I already would be logged in). But as I saw it's not good approach. So I open and close browser for each scenario using the code:

@Before
public void beforeScenario(){
  driver.get("https://example.com");
}

@after
public void afterScenario(){
  driver.close();
}

That's OK for me. But I don't want to create WebDriver for each scenario and I don't want to initialize my POM objects for each scenario.

Now my Before method looks like it:

WebDriver driver;
HomePage home;
LoginPage login;
RegistrationPage reg;

@Before
public void beforeScenario(){
  driver = new ChromeDriver();
  home = new HomePage();
  login = new LoginPage();
  reg = new RegistrationPage();
}

I want to initialize these objects before steps are run and use them in every step.

I research and found out that cucumber-JVM doesn't support @beforeAll hook.

Also I don't want to do some manipulation like:

if( firstTime) {
  //initialise everythin
  firstTime = false
} else {
  //do nothing
}

How can I achieve that? Where can I initialize everything I want before my tests start?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source