Execute all Scenarios in Same Browser Session using Cucumber

Profile picture for user devraj

Using the code below, you can run all your cucumber scenarios in multiple feature files in a single browser session. However, the code will not work correctly with parallel execution due to the use of static variables.

Step 1: Change WebDriver as static in your base class.

public static WebDriver driver;

Base.java

public class Base 
{
	public static WebDriver driver;
		
	public WebDriver getDriver()
	{
		return driver;
	}
	
	public void setDriver()
	{
		System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "//drivers//chromedriverm");
		
		ChromeOptions options = new ChromeOptions();
		options.addArguments("--remote-allow-origins=*");

		driver = new ChromeDriver(options);
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
		driver.manage().window().maximize();
	}
}

Step 2: Change Base Object to static.

static Base base;

Step 3: create a static variable firstSession and set its value to true.

static boolean firstSession = true;	

Step 4: Access static variable using class name in constructor.

public Hooks(Base base)
{
    Hooks.base = base;
}

Step 5: Intialize browser only once in @Before Hook

@Before
public void bf(Scenario scenario) throws IOException
{    
    if(firstSession)
    {	
        base.setDriver();
        firstSession = false;	
    }	
}

Step 6: Quit when all scenarios executed in @AfterAll Hook

@AfterAll
public static void aftAll() throws IOException, EmailException
{
    base.getDriver().quit();
}

Hooks.Java

public class Hooks
{	
	static Base base;		
	static boolean firstSession = true;	
	
	public Hooks(Base base)
	{
		Hooks.base = base;
	}
			
	@Before
	public void bf(Scenario scenario) throws IOException
	{    
		if(firstSession)
		{	
			base.setDriver();
			firstSession = false;	
		}	
	}
	
	@AfterAll
	public static void aftAll() throws IOException, EmailException
	{
		base.getDriver().quit();
	}
}