Я работаю над сценарием с огурцом, в котором Selenium используется для навигации по сайту бронирования отелей, входа в систему и последующего бронирования номера. В коде используются два класса фабрики страниц:
BookRoomLoginPage_PF - Управляет процессом входа в систему.BookRoomBookingPage_PF - Управляет фактическим бронированием номеров.После создания экземпляра BookRoomLoginPage_PF ввод имени пользователя и пароля работает правильно. Однако после входа в систему при попытке забронировать отель с использованием экземпляра BookRoomBookingPage_PF я обнаружил, что объект имеет значение null. Класс, содержащий определения шагов, называется BookRoom.java.
BookRoomBookingPage_PF.java
package pagefactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class BookRoomLoginPage_PF {
private WebDriver driver2;
@FindBy(id = "username")
private WebElement txt_username;
@FindBy(id = "password")
private WebElement txt_password;
@FindBy(id = "doLogin")
private WebElement loginButton;
public BookRoomLoginPage_PF(WebDriver driver1) {
this.driver2 = driver1;
PageFactory.initElements(driver1, this);
}
public void gotWebSite() {
driver2.navigate().to("https://automationintesting.online/#/admin");
}
public void enterUserNameAndPassword(String username, String password) {
txt_username.sendKeys(username);
txt_password.sendKeys(password);
loginButton.click();
}
}
BookRoomBookingPage_PF.java
package pagefactory;
import org.openqa.selenium.*;
import org.openqa.selenium.support.*;
import org.openqa.selenium.support.ui.*;
public class BookRoomBookingPage_PF {
private WebDriver driver;
@FindBy(xpath = "//a[@id='frontPageLink']")
private WebElement frontPageLink;
@FindBy(id = "roomName")
WebElement txt_roomNumber;
@FindBy(id = "type")
WebElement roomTypeDropDown;
@FindBy(id = "accessible")
WebElement accessibleTrueFalse;
@FindBy(id = "roomPrice")
WebElement roomPriceText;
@FindBy(id = "wifiCheckbox")
WebElement wifiCheckBox;
@FindBy(id = "safeCheckbox")
WebElement safeCheckbox;
@FindBy(id = "createRoom")
WebElement createRoomButton;
public BookRoomBookingPage_PF(WebDriver driver1) {
this.driver = driver1;
PageFactory.initElements(driver1, this);
}
public BookRoomBookingPage_PF() {}
public void validateUserReachedBooking() {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement Category_Body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("frontPageLink")));
String frontPageSTring = frontPageLink.getText();
String expectedFrontPageText= "Front Page";
Assert.assertEquals(frontPageSTring, expectedFrontPageText);
}
public void gotWebSite() {
driver.navigate().to("https://automationintesting.online/#/admin");
}
public void enterRoomNumber(String numberForRoom) {
txt_roomNumber.sendKeys(numberForRoom);
}
public void selectRoomType() {
Select selectRoomType = new Select(roomTypeDropDown);
selectRoomType.selectByVisibleText("Family");
}
public void setRoomAccessibility() {
Select selectRoomAccessibility = new Select(accessibleTrueFalse);
selectRoomAccessibility.selectByVisibleText("True");
}
public void enterRoomPrice(String numberForPrice) {
txt_roomNumber.sendKeys(numberForPrice);
}
public void checkWifiBox() {
wifiCheckBox.click();
}
public void checkSafeBox() {
safeCheckbox.click();
}
public void createRoom() {
createRoomButton.click();
}
}
BookRoom.java
package StepDefinitions;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.support.ui.*;
import io.cucumber.java.en.*;
import pagefactory.*;
public class BookRoom {
public WebDriver driver;
public WebDriver driver1 = null;
private BookRoomLoginPage_PF bookRoomLoginPage_PF;
BookRoomBookingPage_PF bookRoomBookingPage_PF;
private ChromeOptions options = new ChromeOptions();
@Given("I am on the booking page")
public void i_am_on_the_booking_page() {
options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
System.setProperty("webdriver.chrome.driver", "C:/path-to-driver/chromedriver.exe");
driver = new ChromeDriver(options);
bookRoomLoginPage_PF= new BookRoomLoginPage_PF(driver);
bookRoomLoginPage_PF.gotWebSite();
bookRoomLoginPage_PF.enterUserNameAndPassword("admin", "password");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
@When("I select the setting")
public void i_select_the_setting() {
driver.findElement(By.id("wifiCheckbox")).click();
}
@And("I select the room type")
public void i_select_the_room_type() {
bookRoomBookingPage_PF.selectRoomType();
}
// Rest of the step definitions...
}
BookRoom.feature
Feature: Verify you can book a room from the non admin website
I want to use this template for my feature file
Scenario Outline: Verify you can book a room
Given I am on the booking page
When I select the setting
And I select the room type
And I set Accessible to true
And I enter <roomnumber> and <price>
And I hit create
Then booking is listed
Examples:
| roomnumber | price |
| 108 | 326 |
Может ли кто-нибудь помочь определить, почему экземпляр BookRoomBookingPage_PF остается нулевым и не выполняется должным образом?




В функции у вас есть:
Given I am on the booking page обрабатывается методом i_am_on_the_booking_page(). Этот метод инициализирует объект BookRoomBookingPage_PF, который используется для управления действиями веб-автоматизации.When I select the setting выполняется методом i_select_the_setting(). В отличие от предыдущего шага, этот метод напрямую использует webdriver, чтобы найти необходимый элемент для действия.And I select the room type, полагаются на методы, вызывающие объект BookRoomBookingPage_PF для управления действиями.Корень проблемы и причина, по которой вы столкнулись с NullPointerException при тестовом запуске, заключается в том, что объект BookRoomBookingPage_PF не был инициализирован в этих последующих методах.
Итак, когда метод i_select_the_room_type() пытается выполнить bookRoomBookingPage_PF.selectRoomType();, он терпит неудачу, поскольку метод не знает об объекте, что приводит к исключению нулевого указателя.
Чтобы решить эту проблему, вам необходимо изменить метод i_am_on_the_booking_page(), чтобы гарантировать правильную инициализацию объекта BookRoomBookingPage_PF.
Вот исправленный код:
@Given("I am on the booking page")
public void i_am_on_the_booking_page() {
options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
System.setProperty("webdriver.chrome.driver",
"C:/Users/Mjrlo/eclipse-workspace/CucumberJava/src/test/resources/drivers/chromedriver.exe");
driver = new ChromeDriver(options);
bookRoomLoginPage_PF= new BookRoomLoginPage_PF(driver);
bookRoomLoginPage_PF.gotWebSite();
bookRoomLoginPage_PF.enterUserNameAndPassword("admin", "password");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Initialize the bookRoomBookingPage_PF after login
bookRoomBookingPage_PF = new BookRoomBookingPage_PF(driver);
}
Я забыл использовать PageFactory.initElements(driver1, this); в моем классе BookRoomBookingPage_PF. Теперь все работает
Я попробовал это и теперь получаю сообщение об ошибке «Невозможно вызвать «org.openqa.selenium.WebElement.click()», потому что «this.safeCheckbox» имеет значение null. Я создал экземпляр bookRoomBookingPage_PF с помощью драйвера, но теперь метод получает нулевую ошибку.