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

Hello Virender,

I think Biresh is worried about getting same driver instance from parent class to all the other classes. As per my understanding, his intention is not with Dataproviders.  I also face the same issue before and got 2 solutions for it but I do not feel them as very best solutions. It would be great if you give some code for us. Below are the 2 ways which I identified.

1. Making driver as a static
2. Creating a constructor in other clases and passsing the driver instance to respective methods (which will be useful when you are returning page factory in Page objects).

Please let me know for any issues.

Many Thanks

Train Answered on March 24, 2015.
Add Comment

Your Answer

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