当前位置:首页>开发>正文

如何使用PageFactory

2023-05-03 08:46:17 互联网 未知 开发

 如何使用PageFactory

如何使用PageFactory

一个简单的例子

为了使用PageFactory,首先需要在PageObject(页面对象)中声明一些元素(WebElements
或 RenderedWebElements),例如:

Java代码

package org.openqa.selenium.example

import org.openqa.selenium.WebElement

public class GoogleSearchPage

{

private WebElement q

public void searchFor(String text)

{

q.sendKeys(text)

q.submit()

}

}
package org.openqa.selenium.example

import org.openqa.selenium.WebElement

public class GoogleSearchPage
{
private WebElement q

public void searchFor(String text)
{
q.sendKeys(text)
q.submit()
}
}

为了让这段代码工作,而不是因为“Q”是不能实例化抛出一个NullPointerException,所以我们需要初始化PageObject:

Java代码

package org.openqa.selenium.example

import org.openqa.selenium.WebDriver

import org.openqa.selenium.WebElement

import org.openqa.selenium.htmlunit.HtmlUnitDriver

import org.openqa.selenium.support.PageFactory

public class UsingGoogleSearchPage

{

public static void main(String[] args)

{

WebDriver driver = new HtmlUnitDriver()

driver.get("http://www.google.com/")

GoogleSearchPage page = PageFactory.initElements(driver, GoogleSearchPage.class)

page.searchFor("Cheese")

}

}
package org.openqa.selenium.example

import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.openqa.selenium.htmlunit.HtmlUnitDriver
import org.openqa.selenium.support.PageFactory

public class UsingGoogleSearchPage
{
public static void main(String[] args)
{
WebDriver driver = new HtmlUnitDriver()
driver.get("http://www.google.com/")
GoogleSearchPage page = PageFactory.initElements(driver, GoogleSearchPage.class)
page.searchFor("Cheese")
}
}

最新文章