15
votes

How to force TestNG create new instance of test class for each method if run mode is parallel="methods"?

JUnit does it automatically but TestNG reuses same instance between methods.

Is there any option to change this behavior?

I'm running selenium tests and create webdriver in @BeforeMethod method and store it to class variable to use it in test methods and clos on @AfterMethod.

And I want to have ability to run methods of one test class in parallel without sharing webdriver.

3
You can achieve the effect you want by simply assigning your fields in the constructor. - Cedric Beust
That wouldn't work--the constructor only gets called once. - shiggity
Managing driver using @BeforeMethod and @AfterMethod is not a good idea. I would suggest to use TestNG with QAF which takes care of driver management and other black-box testing needs utilizing all features of TestNG in best efficient way. - user861594

3 Answers

3
votes

There is no way to force testng to do that. A solution is to set webdriver instance to a threadlocal variable. What this would help doing is, it would create one webdriver object per thread, if u do a get on the variable, it. Would give u that thread's object only.

1
votes

Checkout Factory

From javadoc:

Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[].
0
votes

I've used TestNG to run multiple selenium webdriver tests in parallel. To set up a new WebDriver for each method, use the @DataProvider annotation and its associated attribute in the @Test annotation.