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
内的对象,获取空指针异常
答案 0 :(得分:0)
在基类构造函数中初始化Web驱动程序并在Test类中扩展Base类,然后将驱动程序分配给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();
}
}
Test1课程:
import org.testng.annotations.Test;
public class Test1{
@Test
public void testMethod1()
{
Base base = new Base();
useFunction funObj = new useFunction(base.driver);
funObj.func1();
}
}
尝试一下,让我知道它是否适合你