zupa84pl
zupa84pl

Reputation: 21

testng parallel execution unique object creation

I have class

public class BaseTest {

public WebDriver driver;

@BeforeMethod
public void setup(
driver = new FireFoxDriver();
}

@AfterMethod
public void teardown() {
    driver.quit();
}
}

tests are in extended class

public class Tests extends BaseTest{

@Test
public void first() {
    System.identityHashCode(driver);
}

@Test
public void second() {
    System.identityHashCode(driver);
}
}

testng xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Testing Suite Selenium" parallel="methods" thread-count="5">
<test name="regression">
       <classes>
            <class name="Tests"/>
        </classes>
    </test>
</suite >

I try to execute methods parallel but I see in console that driver object is not unique per test execution. Because of that tests are failing. How I can get unique object per each test instance?

Upvotes: 0

Views: 31

Answers (1)

Krishnan Mahadevan
Krishnan Mahadevan

Reputation: 14746

The problem lies in your test code.

  • TestNG shares the same test class instance across all test methods.
  • Since your test class is using a shared variable (driver) you are experiencing a data race, when your BeforeMethod runs in parallel (because you set parallel="methods" in your suite file)

You should change your base class to look like below. The sample uses ThreadLocal which ensures that every thread gets its own copy of WebDriver in a thread safe manner.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

import java.util.Objects;

public class BaseTest {

    private static final ThreadLocal<WebDriver> driver = new ThreadLocal<>();

    @BeforeMethod
    public void setup() {
        driver.set(new ChromeDriver());
    }

    @AfterMethod
    public void teardown() {
        driver.get().quit();
    }

    protected WebDriver getDriver() {
        return Objects.requireNonNull(driver.get(), "Driver not initialized");
    }
}

Upvotes: 0

Related Questions