RE: How to pass the WebDriver instance to other Class in Selenium/Java/TestNG?

I have Class A and Class B. Class A has the driver initialization and opening the IE browser. I am able to run the test for all the @Test define in Class A which is working fine as expected but I am not able to execute @Test of Class B as the driver instance become NULL.

I tried to use @BeforeSuite and @BeforeTest but it’s not solving my purpose as the driver instance is valid only in Class A.

Can you please suggest me the solution so that I can initialize the driver only once to use for all the remaining Class rather then only for the Class it’s initialize?

I don’t want to create object of Class A and pass it to Class B to access the method.

Thanks in advance for your input.

biresh126 Default Asked on March 24, 2015 in Selenium WebDriver.
Add Comment
10 Answers

Basically there is no limitation of having a static variable or static method to get your webdriver.  You can class those variable or method from anywhere. Try the factory pattern class that I have suggested earlier. However in cases you run tests in parallel you cannot use the same webdriver across all tests even if you have thread synchronized your test. These are the reasons why I say that
– If same driver is being used by mutilple threads your tests will end up waiting on the webdriver object while the other one uses it. It will essential make you tests equal to being synchronized.
– You will also get exceptions because one test will put your driver some state which will be invalid for other test.

For parallel execution you always have to create a new driver per test. I have seen blogs and people talking about sharing a webdriver across truly parallel tests, but I wasn’t able to achieve it. In the comment let me post a sample two step tests which run in parallel, try it for your self.

Professor Answered on March 26, 2015.

Please look at the project shared here, you can run these tests in parallel, in synchronous fashion. Run it and let me know if you have any questions or if it doesnt solve your purpose


on March 26, 2015.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.