如何使用初始化的Webdriver实例从基类到子类java

问题描述 投票:0回答:2
public class Base 
{
    public WebDriver driver;

    @BeforeMethod 
    public void setUp()
    {
        driver = new FirefoxDriver();
    }

}

public class useFunction extends Base
{

    public useFunction(WebDriver driver)
    {
        this.driver = driver;
    }

    public void func1()
    {
        driver.findElement().click();  //driver is null
        --------
        ---------
    }
}

Public class Test extends Base
{
    useFunction funObj = new useFunction(driver);
    @Test
    public void testMethod1()
   {
       funObj.func1();
       ----
       ------ 

  }
}

我如何在

UseFunction class
中使用WebDriver实例的初始化值而不将Webdriver实例声明为静态。当我在
UseFunction class
的构造函数中传递驱动程序同时在
Test class
中创建其对象时,得到空指针异常

java selenium webdriver
2个回答
0
投票

在基类构造函数中初始化网络驱动程序并在测试类中扩展基类,然后将驱动程序分配给Base.driver。

试试下面的代码

基础班:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Base 
{
public WebDriver driver;

public Base(){
    driver = new ChromeDriver();
}
}

UseFunction类:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class useFunction
 {
     WebDriver driver;

  public useFunction(WebDriver driver)
  {
    this.driver = driver;
  }

  public void func1()
  {
    driver.findElement(By.id("id of the element")).click(); 
  }
  }

测试1班:

import org.testng.annotations.Test;

public class Test1{

@Test
public void testMethod1()
{
    Base base = new Base();
    useFunction funObj = new useFunction(base.driver);
    funObj.func1(); 

}
}

试一试,让我知道它是否适合你


0
投票
public WebDriver Base()
{
    
    WebDriverManager.edgedriver().setup(); //Change for Chrome.
    
    EdgeOptions options = new EdgeOptions();
    options.addArguments("--remote-allow-origins=*");
    
    WebDriver ed = new EdgeDriver(options);
    ed.manage().window().maximize();
    ed.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
    
    return ed;
}

//测试1

公共类 Test1 扩展 Base {

public void Test1_TestNG() throws InterruptedException
{

    WebDriver ed = Base();
    ed.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
    

//现在您可以将“ed”WebDriver 用于任何方法(或)进一步基于 Web 的自动化,只需调用“ed”WebDriver。

}

}

© www.soinside.com 2019 - 2024. All rights reserved.