我在wait.until()方法中创建了一个自定义的ExpectedCondition作为输入,但是当我的代码到达我的自定义ExpectedCondition参数时,抛出了NullPointerException,我无法弄清楚原因。我已经尝试了所有的东西,并且始终收到相同的结果。下面,您将找到我的代码
CustomWait:
public static ExpectedCondition<Boolean> visibilityOfElement(final
WebElement element) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver input) {
try {
return element.isDisplayed();
}catch(NoSuchElementException e) {
return false;
}catch(StaleElementReferenceException e1) {
return false;
}
}
};
}
}
LoginPage(此页面包含调用CustomWait类方法的代码):
public class LoginPage {
WebDriver driver;
WebDriverWait wait;
@FindBy(how=How.ID, using="email") WebElement email;
@FindBy(how=How.ID, using="password") WebElement password;
@FindBy(how=How.ID, using="submit-button") WebElement loginSubmitButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String email, String password) {
wait.until(CustomWait.visibilityOfElement(this.email));
this.email.sendKeys(email);
this.password.sendKeys(password);
loginSubmitButton.click();
}
}
当程序到达代码&#34; wait.until(CustomWait.visibilityOfElement(this.email))&#34;时,就是抛出NullPointerException,我相信&#34; WebDriver输入& #34; Custom Wait类的visibilityOfElement方法的参数的一部分是问题所在,但我无法弄清楚原因。
Main(这是我的测试的地方):
public class Main {
WebDriver driver;
public Main() {
driver = BrowserFactory.startBrowser("chrome",
"http://123help123.com/");
}
@Test
public void smokeTest() {
HomePage homePage = PageFactory.initElements(driver,
HomePage.class);
homePage.clickLogin();
LoginPage loginPage = PageFactory.initElements(driver,
LoginPage.class);
loginPage.login("haha", "123");
}
}
BrowserFactory(这是我的驱动程序的创建方式):
public class BrowserFactory {
static WebDriver driver;
public static WebDriver startBrowser(String browser, String url) {
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("chrome")) {
if(SystemUtils.IS_OS_MAC_OSX) {
System.setProperty("webdriver.chrome.driver",
"src/chromedriver");
}
else if(SystemUtils.IS_OS_WINDOWS) {
System.setProperty("webdriver.chrome.driver",
"src/chromedriver.exe");
}
driver = new ChromeDriver();
}
else if(browser.equalsIgnoreCase("ie")) {
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
非常感谢任何帮助,如果您需要更多信息,请告知我们。
答案 0 :(得分:2)
你得到了NullPointerException,因为你还没有在LoginPage类中初始化 wait 。因此,没有驱动程序可以传递给您的自定义ExpectedCondition。
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver,5);
}