java - TestNG @BeforeClass 初始化代码在 Test 之前未运行

标签 java selenium junit testng

我正在使用 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/

相关文章:

java - 多种类型的相同接口(interface)

Java 控制台在 AMD 64 位平台上无法运行 : Can't load IA 32-bit . dll

unit-testing - 修复现有的 JUnit 以使其在添加新代码后通过测试是否是一种好的做法?

java - Mockito when()...then() NullPointerException

java - JUnit 错误 : Could not find or load main class (RemoteTestRunner)

java - 通过 Google Sheets api v4 将新工作表添加到现有电子表格

java - 网络协议(protocol)的设计模式?

python - 更改 Pandas Dataframe 中的数据类型

java - 无法实例化类异常TestNG

python - Selenium:如何禁用 firefox 和 python 的图像加载?