How to do session handling in Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can perform session handling with the help of Selenium webdriver with a TestNG framework. To trigger different sessions, we shall use the attribute parallel in the TestNG XML file.

A TestNG execution configuration is done in the TestNG XML. To create multiple sessions, we shall add the attributes – parallel and thread-count in the XML file.

The attribute thread-count controls the number of sessions to be created while executing the tests in a parallel mode. The value of parallel attribute is set to methods.

In our example, we would have three methods with three different session ids which are executing in parallel.

Example

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.SessionId;
public class TestNG10 {
   @Test
   public void myTest () {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/index.htm");
      //get session ID
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }@Test
   public void myTest1 () {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.google.com/");
      //get session ID
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }@Test
   public void myTest2 () {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm/");
      //get session ID
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }
}

TestNG XML Implementation.

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<!—parallel methods set for execution with 3 threads-->
<suite name="Test-Suite" parallel="methods" thread-count="3">
   <test name="Tutorialspoint" >
      <classes>
         <class name="TestNG10" />
      </classes>
   </test>
</suite>

Output

raja
Published on 08-Apr-2021 11:26:18
Advertisements