Chrome Driver - testNG parallel issue



  • I am trying to run selenium test classes parallel using testNG like this

    thread-count="3" parallel="classes"

    . But the issue is at closing the chrome driver and everything else works fine. while execution some of the browsers getting closed even before executing the all the test cases throwing SessionNotFoundException.

    code snippet as follows in BrowserUtil.java class:

    public static WebDriver driver=null;
    
    private static volatile ThreadLocal<WebDriver> tLocal = new ThreadLocal<WebDriver>();
    public static synchronized void create() {
    WebDriver driver1=new ChromeDriver();
    
    tLocal.set(driver1);
    
    driver = getDriver();
    
    driver.manage().window().maximize();
    }
    
    
    public static WebDriver getDriver() {
        WebDriver driv = tLocal.get();
    
        return driv;
    
    }
    
    
    public synchronized static void destroy()
    {
    
        logger.debug("----Closing browser----");
    
        driver.close();
    }
    

    Test class as follows:

    @BeforeClass
    public void navigateToPage() throws Exception {
            BrowserUtil.create();
    
    }
    
    @AfterClass
    public void close() {
        BrowserUtil.destroy();
    
    }
    


  • You shouldn't make the driver static.

    I am not a Java expert, but I think static classes only exist once. Meaning that any reference to the static objects are the same. You are trying to maintain multiple states in a single static (global) class.

    Static Variables: When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

    https://www.geeksforgeeks.org/difference-between-static-and-non-static-variables-in-java/

    I think you should build a factory that returns a unique driver object with create and destroy methods to be used in your tests.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2