Reputation: 101
Class that contains all classes
public class AllTests{
public static void main(String[] args) {
Loginer.login();
Example.linkOne();
Examplee.linkTwo();
}
}
Class that starts the Firefox driver and logins
public class Loginer{
public static login(){
WebDriver driver = new FirefoxDriver();
driver.get("http://LINKISHERE.COM/");
//other login code
}
}
Actual Selenium code that clicks links and stuff
public class Example{
public static linkOne() {
**driver**.findElement(By.className("CLASSNAME")).click();
}
public static linkTwo() {
**driver**.findElement(By.className("CLASSNAME")).click();
}
}
I'm pretty new to JAVA, I only worked with python till now.
What I'm trying to do is have multiple tests split into multiple classes that are part of the AllTests class, so I can take them out or add new ones with easy.
My trouble has been using the same WebDriver in all classes due to this java.lang.NullPointerException
. Is this recommended or should it be fine to have Selenium start a new WebDriver every time?
Upvotes: 1
Views: 2388
Reputation: 6577
Initialize the driver in the AllTests
class and pass it along to the others as a method argument.
public class AllTests {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
Loginer.login(driver);
Example.linkOne(driver);
Examplee.linkTwo(driver);
}
}
public class Loginer {
public static void login(WebDriver driver){
driver.get("http://LINKISHERE.COM/");
// other login code
}
}
public class Example {
public static void linkOne(WebDriver driver) {
driver.findElement(By.className("CLASSNAME")).click();
}
}
public class Examplee {
public static void linkTwo(WebDriver driver) {
driver.findElement(By.className("CLASSNAME")).click();
}
}
Upvotes: 3
Reputation: 5347
You can change your classes as given below.
public class Loginer{
public static WebDriver driver;
public static login(){
driver = new FirefoxDriver();
driver.get("http://LINKISHERE.COM/");
//other login code
}
}
public class Example{
public static linkOne() {
Loginer.driver.findElement(By.className("CLASSNAME")).click();
}
}
public class Examplee{
public static linkTwo() {
Loginer.driver.findElement(By.className("CLASSNAME")).click();
}
}
Here, I am storing the driver instance in a static variable and using it in all classes. It may works for you.
Upvotes: 3