我是第一次使用 Selenium 和 TestNG,我一直在尝试按 ID 搜索元素,但我不断收到“无法实例化类”错误。这是我的代码:
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
public class NewTesting {
WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setUp() {
driver.get("http://book.theautomatedtester.co.uk/chapter1");
}
@AfterTest
public void tearDown() {
driver.quit();
}
@Test
public void testExample() {
WebElement element = driver.findElement(By.id("verifybutton"));
}
}
也许我错过了安装某些东西?我安装了 eclipse 的 TestNG 插件并添加了 WebDriver JAR 文件,我还需要执行更多操作吗? 我尝试遵循多个教程,但我不断收到错误,我希望有人能提供帮助。提前致谢!
编辑: 我现在有这个:
public class NewTest {
private WebDriver driver;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.gecko.driver","C:\\Program Files\\Selenium\\FirefoxDriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://book.theautomatedtester.co.uk/chapter1");
}
@AfterTest
public void tearDown() {
driver.quit();
}
@Test
public void testExample() {
WebElement element = driver.findElement(By.id("verifybutton"));
}
}
它现在确实打开了网站,但我现在遇到了空指针异常:
配置失败:@AfterTest TeaDown java.lang.NullPointerException 在 NewTest.tearDown(NewTest.java:21)
最佳答案
替换这组导入:
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
与:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
此外,您必须从 mozilla/geckodriver 下载所需格式的 GeckoDriver 可执行文件。 ,提取二进制文件,然后初始化 FirefoxDriver。
您的有效代码块将是:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
public class NewTesting {
WebDriver driver;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.gecko.driver","C:\\path\\to\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("http://book.theautomatedtester.co.uk/chapter1");
}
@AfterTest
public void tearDown() {
driver.quit();
}
@Test
public void testExample() {
WebElement element = driver.findElement(By.id("verifybutton"));
}
}
关于java - 通过 Selenium Java TestNG 执行测试时出现 "Cannot instantiate class"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53070732/