将驱动程序对象的单个实例传递给所有其他类(Testng 框架)

Vic*_*cky 3 testng selenium-webdriver

我有一个在类示例中初始化的驱动程序对象。我也想将驱动程序对象传递给其他类,但我得到一个空指针异常。我的代码是

样本类

    public class sample {

    WebDriver driver ;


    @Test(priority=1)

    public void openbrowser(){


        System.setProperty("webdriver.chrome.driver",
                "/home/ss4u/Desktop/Vignesh/jars/chromedriver");

        driver = new ChromeDriver();

        driver.get("http://www.google.com");

        System.out.println(driver instanceof WebDriver);


    }
   @Test(priority=2)
   public void maximize(){

      driver.manage().window().maximize();

   }
   @Test(priority=3)
   public void transfer_instance(){

       sampleone obj=new sampleone(driver);


   }

}
Run Code Online (Sandbox Code Playgroud)

样本类

public class sampleone {

    WebDriver driver;

    public sampleone(WebDriver driver){

        this.driver=driver;

        System.out.println(driver instanceof WebDriver);

        System.out.println(this.driver instanceof WebDriver);

        System.out.println("constructor2");


    }

  public sampleone(){

        System.out.println("Default constructor called");


    }


    @Test(priority=1)

     public void gettitle(){

          System.out.println(this.driver instanceof WebDriver);

          System.out.println(driver instanceof WebDriver);

          String title=this.driver.getTitle();

          System.out.println(this.driver instanceof WebDriver);

          System.out.println(title);

          Assert.assertEquals(title, "Google");

        }

    @Test(priority=2)

    public void navigate(){

        this.driver.get("https:in.yahoo.com");

    }

}
Run Code Online (Sandbox Code Playgroud)

测试xml文件

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestNG" verbose="1" >

    <test name="sample test">
    <classes>
      <class name="testsample.sample" />
    </classes>
    </test>

    <test name="sample testone">
    <classes>
      <class name="testsample.sampleone" />
    </classes>
    </test>

</suite>
Run Code Online (Sandbox Code Playgroud)

发生此问题是因为我不使用创建的对象而是使用 testng.xml 文件调用类,是否有任何可能的方法来创建新的 java 实例(所有类通用)或在所有类中使用现有实例

Vic*_*cky 5

我自己找到了一个解决方案...当我详细阅读 testng 时,我发现 testng xml 文件调用了 xml 文件中指定的所有类的默认构造函数。因此,即使我们将对象传递给另一个类,我们也无法执行该操作通过对象,所以发生空指针异常......我发现了两个解决方案,第一个是使用pagefactory,第二个是为您的测试套件使用通用驱动程序类......这样我们就可以使用相同的驱动程序实例所有课程

通用驱动类

public class Driver {

    public static WebDriver driver=null;



    public static WebDriver startdriver(String browser){


        if(browser.equalsIgnoreCase("Chrome")){

        System.setProperty("webdriver.chrome.driver", "/home/vicky/Documents/Jars/chromedriver");

        driver=new ChromeDriver();

        }else if(browser.equals("Firefox")){

        driver=new FirefoxDriver();

        }
        return driver;

        }

    }
Run Code Online (Sandbox Code Playgroud)