I have defined an object of Web driver in one class as
Static WebDriver driver;
and want to use that instance in another class to automate the browser. Is it possible? Or will I have to define drivers every time in each class?
I tried by defining a webdriver in another class as:
Static webDriver AnotherDriver;
and then assigning it the value of other driver as:
AnotherDriver = ClassName.driver;
But I am getting nullPointer Exception when I using AnotherDriver.
And if I have to define a new driver in each class then I will get stuck, as I have defined some methods which I will be using in other class file and all of them use the driver defined in that class.
Any kind of suggestion is highly appreciated.
3 Answers 3
Approach 1
- Create a class, for example
Hull
. - In the class is a
protected
variableWebDriver driver
. - In the class is a method
setup()
with a@Before
annotation. - In the method you has a condition: Is
WebDriver
null
, initialize; else do nothing. - Classes with test cases extends from
Hull
. - Classes with test cases can use the variable
driver
.
Approach 2
- Create a class, for example
Hull
. - In the class is a
private
variableWebDriver driver
. - In the class is a method
getDriver()
. - In the method you has a condition: Is
WebDriver
null
, initialize; else do nothing. - Classes with test cases extends from
Hull
. - Classes with test cases can use the
getDriver()
method to use theWebDriver
. Tip: Use always this method if you interact with theWebDriver
, because so you are save that theWebDriver
will be initialized.
-
is it possible that I open browser with a driver and access web contents with the another driver by defining it as: SecondDriver = classname.firstDriver;Ashwani Raj– Ashwani Raj2014年07月07日 13:00:54 +00:00Commented Jul 7, 2014 at 13:00
-
2@razizcool4all I do not know. Try it! Print the value of
firstDriver
andsecondDriver
. If they have the same value, it should be possible. But why you want to do something like that?Twaldigas– Twaldigas2014年07月07日 13:14:03 +00:00Commented Jul 7, 2014 at 13:14 -
I want to define the link to test in one function and open that link first whenever I have to run test cases. So here i came up with a problem that if I initiate browser with one driver we can't access it with other driver. So to resolve this I have to use another instance of the same driver.Ashwani Raj– Ashwani Raj2014年07月08日 07:32:18 +00:00Commented Jul 8, 2014 at 7:32
you can pass the driver as argument to the methods , so no need to re create them.
Generally, it is bad practice to set the WebDriver instance as static.
You should create a base class that each of your test classes extend so that each test class has its own instance of WebDriver to be used (this is especially important with parallel execution), then just declare/define your WebDriver variable within that base class.
Explore related questions
See similar questions with these tags.
driver
variable. Uninitialized variables may causeNullPointerException
.