我正在使用 Selenium、TestNG 编写测试代码。当我在同一页面上重复这些操作时,我尝试在 @BeforeClass
部分设置一些元素。但我收到空指针异常。有办法解决这个问题吗?
public class RunTest {
private static WebElement user;
private static WebElement pass;
private static WebElement login;
@BeforeClass
public static void driveraBaglan() {
//Driver is declared here. I removed it to give the simple code.
user = driver.findElement(By.id("user"));
pass = driver.findElement(By.id("pass"));
login = driver.findElement(By.xpath("//button[contains(.,'Log In')]"));
statusMessage = driver.findElement(By.id("login-status-message")).getText();
}
@Test(priority=1)
public void loginNoInfo() {
user.clear();
pass.clear();
}
我在 user.clear()
、 pass.clear()
和 login.click()
函数上遇到空指针错误。页面上的所有测试都在同一页面上运行。我不想在页面上的每个测试中使用重复的“按 id 查找元素”标签。
最佳答案
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. @BeforeClass: The annotated method will be run before the first test method in the current class is invoked
尝试更改注释
@BeforeTest
public static void driveraBaglan() {
//Driver is declared here. I removed it to give the simple code.
user = driver.findElement(By.id("user"));
pass = driver.findElement(By.id("pass"));
login = driver.findElement(By.xpath("//button[contains(.,'Log In')]"));
statusMessage = driver.findElement(By.id("login-status-message")).getText();
}
关于java - TestNG @BeforeClass 初始化代码在 Test 之前未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49463014/