【问题标题】:Same instance of Webdriver in multiple classes in Java SeleniumJava Selenium 中多个类中的相同 Webdriver 实例
【发布时间】:2018-03-21 19:47:30
【问题描述】:

包含所有类的类

public class AllTests{
    public static void main(String[] args) {
        Loginer.login();
        Example.linkOne();
        Examplee.linkTwo();
    }
}

启动 Firefox 驱动程序和登录的类

public class Loginer{
    public static login(){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://LINKISHERE.COM/");
        //other login code
    }
}

点击链接和内容的实际 Selenium 代码

public class Example{

    public static linkOne() {
            **driver**.findElement(By.className("CLASSNAME")).click();
    }

    public static linkTwo() {
            **driver**.findElement(By.className("CLASSNAME")).click();
    }
}

我对 JAVA 很陌生,到目前为止我只使用过 python。 我想要做的是将多个测试拆分为多个属于 AllTests 类的类,因此我可以轻松地将它们取出或添加新的。 由于java.lang.NullPointerException,我的麻烦一直是在所有课程中使用相同的 WebDriver。这是推荐的还是让 Selenium 每次都启动一个新的 WebDriver 就可以了?

【问题讨论】:

  • 你会如何在 python 中做到这一点?
  • 查看 TestNG 以及有关如何开始的许多示例。

标签: java selenium selenium-webdriver


【解决方案1】:

AllTests 类中初始化驱动程序并将其作为方法参数传递给其他人。

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

【讨论】:

  • 这行得通,简直不敢相信是那么容易。非常感谢。可以这样传递多个变量吗?例如:变量“i”随着每次调用“i++”而增加值
【解决方案2】:

您可以如下所示更改您的课程。

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

    }
}

在这里,我将驱动程序实例存储在一个静态变量中,并在所有类中使用它。它可能对你有用。

【讨论】:

    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 2012-07-29
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多