Я получаю исключение нулевого указателя в классе объектов страницы, почему я получаю NPE

#java #selenium-webdriver

#Ява #селен-веб-драйвер

Вопрос:

 Base class package resources;  import java.io.FileInputStream; import java.io.IOException; import java.time.Duration; import java.util.Properties;  import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;  import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert;   public class base {  public WebDriver driver; public Properties property; public String url= "qwerty";    public WebDriver initializeDriver() throws IOException {      property = new Properties();  FileInputStream file = new FileInputStream("D:\qwe\rty\src\main\java\resources\data.properties");    property.load(file);  String BrowserName = property.getProperty("browser");    if(BrowserName.equals("chrome"))   {  System.setProperty("webdriver.chrome.driver", "D:qwe\rty\chromedriver.exe");   driver = new ChromeDriver();    }  else if(BrowserName.equals("firefox"))   {  driver = new FirefoxDriver();  }  else if(BrowserName.equals("IE"))   {  //Executes IE  }  driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));  return driver; }  public WebDriver verifyPage() {    driver.get(url);  String Expected = driver.findElement(By.cssSelector("p[class='login-box-msg']")).getText();  String Actual = "Sign in to start your session";  Assert.assertEquals(Actual, Expected);  System.out.println("Homepage is displayed");  return driver; } }  Page Object class  

Я получаю NPE в методе user() в этой строке возвращаемый драйвер.findElement(имя пользователя);

 package pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;   public class LoginPage {  public WebDriver driver;  By username = By.xpath("//input[@type='text']"); By password = By.xpath("//input[@type='password']"); By login = By.xpath("//button[@type='submit']"); By profile = By.xpath("//li[contains(@class,'nav-item dropdown user-menu')]/a[1]/img"); By logout = By.xpath("//li[@class='user-footer']/a[1]");      public LoginPage(WebDriver driver) {    this.driver = driver;   }   public WebElement user() {   return driver.findElement(username); }  public WebElement pass() {   return driver.findElement(password); }  public WebElement signIn() {   return driver.findElement(login); }  public WebElement pro() {   return driver.findElement(profile); }  public WebElement signOut() {   return driver.findElement(logout); }  }  Testcase  

Когда я запускаю testcase при вызове lp.user (), возникает ошибка NPE в классе объектов страницы

 package Admission;  import java.io.IOException; import java.time.Duration;   import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test;  import pageObjects.LoginPage; import resources.base;   public class homePage extends base{   public WebDriver driver; LoginPage lp = new LoginPage(driver);  @Test public void loginDetails() throws IOException, InterruptedException {    driver=initializeDriver();  verifyPage();      WebElement aadharNo = lp.user();  aadharNo.sendKeys("111111111111");    WebElement password = lp.pass();  password.sendKeys("21102021");    WebElement submit = lp.signIn();  submit.click();      WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));   wait.until(ExpectedConditions.visibilityOf(lp.pro())).click();    WebDriverWait wait1 = new WebDriverWait(driver, Duration.ofSeconds(10));   wait1.until(ExpectedConditions.visibilityOf(lp.signOut())).click();   }   @Test  public void testCase() {    WebElement aadharNo = lp.user();  WebDriverWait wait2 = new WebDriverWait(driver, Duration.ofSeconds(30));   wait2.until(ExpectedConditions.visibilityOf(aadharNo));  aadharNo.sendKeys("111111111111");    WebElement password = lp.pass();  WebDriverWait wait3 = new WebDriverWait(driver, Duration.ofSeconds(20));   wait3.until(ExpectedConditions.elementToBeSelected(password));  password.sendKeys("hgfhg");  lp.signIn(); } }  

java.lang.Исключение NullPointerException: Не удается вызвать «org.openqa.selenium.WebDriver.findElement(org.openqa.селен.By)», потому что «this.driver» имеет значение null в PageObjects.Страница входа.пользователь(страница входа.java:31) при поступлении.Домашняя страница.тестОвый кейс(домашняя страница.java:52)

Комментарии:

1. Вы инициализируетесь driver после построения LoginPage .

2. да, я пытался, но все равно получаю тот же NPE

3. Ты пробовал что?

4. публичная страница входа(драйвер веб-драйвера) { this.driver = драйвер; } Публичный драйвер веб-драйвера; Нравится это ?

5. драйвер=инициализированный драйвер(); lp = новая страница входа(драйвер); … Проверка страницы();

Ответ №1:

Вам необходимо initializeDriver() перед созданием LoginPage объекта:

 public class homePage extends base{  public WebDriver driver = initializeDriver();  LoginPage lp = new LoginPage(driver);   @Test  public void loginDetails() throws IOException, InterruptedException {  verifyPage();    WebElement aadharNo = lp.user();  aadharNo.sendKeys("111111111111");    WebElement password = lp.pass();  password.sendKeys("21102021");    WebElement submit = lp.signIn();  submit.click();      WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));   wait.until(ExpectedConditions.visibilityOf(lp.pro())).click();    WebDriverWait wait1 = new WebDriverWait(driver, Duration.ofSeconds(10));   wait1.until(ExpectedConditions.visibilityOf(lp.signOut())).click();   }   (...) }  

Комментарии:

1. Спасибо, это работает

2. Классно! В этом случае примите ответ как правильный, чтобы ваш вопрос можно было «закрыть» и другие могли извлечь из него пользу 😉 Спасибо!