gpt4 book ai didi

java - 如何初始化驱动程序以避免 NullPointerException 错误

转载 作者:行者123 更新时间:2023-11-30 06:11:36 25 4
gpt4 key购买 nike

我在使用此类时遇到问题,收到空指针异常。我插入System.out.println("driver=" + driver);查看输出内容,它指出 driver=null对于每个数据集,当我点击@Test下的方法时,这让我认为初始化存在问题。如何解决驱动程序的初始化以使我的测试在 testNG 中通过?

下面是代码:

package com.testng.practice;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class LoginTest {

WebDriver driver = null;

@BeforeTest
public void invokeApplication() {
System.setProperty("webdriver.chrome.driver", "xxx\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
}

@Test (dataProvider = "getData")
public void loginFaceBook(String email, String password) {

System.out.println("driver=" + driver);

WebElement emailField = driver.findElement(By.name("email"));
WebElement passwordField = driver.findElement(By.name("pass"));

emailField.sendKeys(email);
passwordField.sendKeys(password);

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@DataProvider
public Object[][] getData(){

//declared object of 4 rows and 2 columns

Object[][] dataSet = new Object[4][2];

dataSet[0][0] = "TimSmith@gmail.com";
dataSet[0][1] = "Smith123";

dataSet[1][0] = "JaneMcCormack@gmail.com";
dataSet[1][1] = "McCormack123";

dataSet[2][0] = "AnjaliPrakash@gmail.com";
dataSet[2][1] = "Prakash123";

dataSet[3][0] = "JamesBean@gmail.com";
dataSet[3][1] = "Bean123";

return dataSet;

}
}

最佳答案

driver 变量的定义在 invokeApplication() 方法中有效,并且使类属性 driver 未初始化

WebDriver 驱动程序 = new ChromeDriver();

初始化类属性使用:

this.driver = new ChromeDriver();

关于java - 如何初始化驱动程序以避免 NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com