我是Selenium Java编程初学者。当我用TestNG执行下面的脚本时,我遇到了一个错误。
错误消息
, . lang。NullPointerException:无法调用"org.openqa.selenium.WebDriver.findElement (org.openqa.selenium.By)";因为"this.driver"null"
Please Check Below Code And Suggest Changes.
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
public class RegForm {
public WebDriver driver;
@BeforeTest
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D://Selenium//ChromeDriver//chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php");
driver.manage().window().maximize();
Thread.sleep(3000);
}
@Test
public void TC01() throws Exception {
driver.findElement(By.xpath("//*[@id="header"]/div[2]/div/div/nav/div[1]/a")).click();
Thread.sleep(3000);
}
}
将WebDriver
从main
中移除,如下所示
public static WebDriver driver;
@BeforeTest
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D://Selenium//ChromeDriver//chromedriver");
driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php");
driver.manage().window().maximize();
Thread.sleep(3000);
}
如果您不使用MAC,然后尝试提供chromedriver扩展.exe
,还检查@Test
的导入,因为您提到您正在使用testng
在测试类中创建驱动程序并不是一个好主意。
实现类似的东西可能是个好主意
同样的问题浪费了整整一天。请检查您是否在任何其他类中定义了web驱动程序。如果是,则将其设置为protected并使用此类扩展。
protected static WebDriver driver;