[英]NullpointerException while invoking SendKeys through Selenium using PageFactory with Page Object
我有三節課。 一種用於從網頁中獲取所有元素,一種用於對這些元素執行操作,另一種用於測試腳本。 從測試腳本調用函數時,出現空指針異常。 我發現這是因為我使用@FindBy批注,但是我不知道如何解決此問題。
元素類:
public class LoginPageElements {
@FindBy(id="loginId")
private static WebElement userNameTextBox;
@FindBy(id="password")
private static WebElement userPasswordTextBox;
@FindBy(id="QTP_LoginButton")
private static WebElement loginButton;
public static WebElement getUserNameTextBox(WebDriver driver){
WebElement a=driver.findElement(By.id("loginId"));
return a;
}
public static WebElement getUserPasswordTextBox(){
return userPasswordTextBox;
}
public static WebElement getLoginButton(){
return loginButton;
}
}
動作類:
public class LoginPageActions {
public static void login(WebDriver driver,String username,String password){
WebElement a=LoginPageElements.getUserNameTextBox(driver);
a.sendKeys(username);
LoginPageElements.getUserPasswordTextBox().sendKeys(password);
LoginPageElements.getLoginButton().click();
}
}
測試腳本:
public class Sample {
public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", driverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("--enable-automation");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
options.setExperimentalOption("useAutomationExtension", false);
driver = new ChromeDriver(options);
driver.get("http://10.235.80.106:8080");
LoginPageActions.login(driver,"acb", "adasd");
}
當我將WebDriver對象從測試腳本傳遞到元素類時,也不例外。 由於沒有WebDriver實例化,當我使用通過FindBy注釋初始化的元素時,會發生問題。 我該如何解決? 謝謝
您可以繼續使用@FindBy批注,只需要確保對WebElements進行初始化即可。 為此,您應該使用PageFactory初始化LoginPageElements:
LoginPageElements loginPageElements = PageFactory.initElements(webDriver, LoginPageElements.class);
其中webDriver是用於運行硒測試的WebDriver的實例。
您需要聲明WebDriver
實例,並在LoginPageElements
和LoginPageActions
類中添加構造函數,如下所示:
LoginPageElements
類:
WebDriver driver; //constructor public LoginPageElements(WebDriver loginDriver) { this.driver=loginDriver; }
LoginPageActions
類:
WebDriver driver; //constructor public LoginPageActions(WebDriver loginDriver) { this.driver=loginDriver; }
讓我知道這是否回答了您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.