我有三個類。一個用於從網頁獲取所有元素,一個用於執行這些元素的操作,另一個用於測試腳本。當我從測試腳本中調用一個函數時,我得到一個空指針異常。我想通了這是因爲我使用@FindBy註釋,但我不知道如何解決這個問題。使用SendKeys時Selenium中的NullpointerException
要素類:
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和WebElement a = driver.findElement(By.id(「loginId」));? – Plog
複製堆棧跟蹤中的零點異常到你的問題.. – StefanE
我不是故意冒犯你@ kaushik3993,但你卻缺少關於面向對象編程的知識。嘗試瞭解一下'constructor'是什麼,'static'關鍵字如何影響你的代碼。 –