我第一次使用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拆卸 java.lang.NullPointerException 在NewTest.tearDown(NewTest.java:21)
答案 0 :(得分:1)
如果您在Windows上,this上一个问题可能会对您有所帮助。
它提到您可以download geckodriver,然后像这样初始化FirefoxDriver:
System.setProperty("webdriver.gecko.driver","G:\\Selenium\\Firefox driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
答案 1 :(得分:1)
替换这组导入:
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"));
}
}