简体   繁体   中英

Same instance of Webdriver in multiple classes in Java Selenium

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?

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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM