Sharing driver between @BeforeMethod and @AfterMet

2019-07-27 00:54发布

问题:

I am writing tests in testNG. Each test method shares a number of common attributes stored at the class level but each test method needs its own independent driver, so the driver cannot be stored as a class variable. This allows each test method to be invoked multiple times with different drivers while running concurrently.

Basically my sudo-code of what I am trying to do would look something like the following:

@BeforeMethod
public void setup(Argument someArg) {
    Driver driver = new Driver(argArg); 
}

@Test
public void test() {
    driver.dostuff();
}

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

My thought is that I might store the drivers in a concurrent map collection using the classname and test method as a key for storing and retrieving the driver, but I would like to find a simpler, less verbose way of doing this.

I apologize if there is an answer that already addresses this. I searched high and low and couldn't find the solution I was looking for or couldn't make the connection to how a specific idea would apply to my problem. My case is specific to Selenium Webdriver, but I imagine that there are other cases that may want to do something like this.

回答1:

How about using a ThreadLocal<Driver>?