在 Selenium 中使用页面对象模型的 NullPointerException

NullPointerException using Page Object Model in Selenium

我目前正在尝试通过在其中实施页面对象模型来改进我的 Selenium 测试用例。但是,我正在测试的网站处理很多模式。当我尝试访问某些模式时,我得到一个 NullPointerException。我不知道驱动程序是不是在等待元素还是什么。

这是我的 classes:

页面对象

public class ManualShipmentModal
{
WebDriver driver;
WebDriverWait wait;

@FindBy(id = "manual-order-modal")
WebElement modalBody;

@FindBy(name = "mailToName")
WebElement toName;

/* Constructor */
public ManualShipmentModal(WebDriver driver)
{
    this.driver = driver;
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

    AjaxElementLocatorFactory factory = new AjaxElementLocatorFactory(driver, 100);
    PageFactory.initElements(factory, this);
}

public boolean modalExists()
{
    return modalBody.isDisplayed();
}

public void enterToAddress(String toName, String addressName)
{
    wait.until(ExpectedConditions.visibilityOf(modalBody));
    WebElement toAddress = driver.findElement(By.linkText(addressName));

    this.toName.sendKeys(toName);
    toAddress.click();
}

}

测试class

public class TEST_11
{

WebDriver driver;

LoginPage loginPageObj;
HeaderMenu headerMenuObj;
ManualShipmentModal manualShipmentModalObj;

@Before
public void setup()
{
    driver = new ChromeDriver();
    driver.get("testpage.com");
}

@Test
public void testCreateNewShipment()
{
    loginPageObj = new LoginPage(driver);
    headerMenuObj = new HeaderMenu(driver);
    manualShipmentModalObj = new ManualShipmentModal(driver);

    loginPageObj.login("username", "password");
    headerMenuObj.createNewShipment();
    manualShipmentModalObj.enterToAddress("Test", "The Usual Test");
}

@After
public void teardown()
{
    driver.close();
}
}

它运行良好,直到我调用 enterToAddress()。当到达那个点时,它会抛出 NullPointerException。驱动程序似乎没有等待元素加载,即使我定义了隐式等待和显式等待。

WebDriverWait wait 未实例化,因此调用它会抛出 NullPointerException.

ManualShipmentModal的构造函数中使用它的构造函数:

public ManualShipmentModal(WebDriver driver)
{
    this.driver = driver;
    long timeOutInSeconds = 10; // just an arbitrary value example
    this.wait = new WebDriverWait(driver, timeOutInSeconds);

    // the rest of your constructor as in the original code
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

    AjaxElementLocatorFactory factory = new AjaxElementLocatorFactory(driver, 100);
    PageFactory.initElements(factory, this);
}