本文共 1399 字,大约阅读时间需要 4 分钟。
在学习selenium中page obiect记录,采用分层思想,页面元素与测试方法分离出来;
page方法可以把页面元素放到该方法中:
页面类:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class BDPage { //定义元素变量 /**定义百度搜索的输入框*/ @FindBy(id="kw") //查找定义 @FindBy(name/className/xpath/css="kw") @CacheLookup //找到元素之后缓存起来,重复使用这些元素,加快测试速度 public WebElement keyword_input; /**定义百度搜索的搜索按钮*/ @FindBy(id="su") @CacheLookup public WebElement search_button; public BDPage(WebDriver driver) { PageFactory.initElements(driver, this); } }实体类:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class BDPageTest { WebDriver driver; @Test public void Testpd() { //实例化BDPage对象 BDPage bdp = new BDPage(driver); //bdp调用keyword_input元素,然后使用元素的sendKeys方法向输入框输入“你好” bdp.keyword_input.sendKeys("你好"); //bdp调用search_button元素,然后调用元素的click方法点击搜索按钮 bdp.search_button.click(); } @BeforeTest public void beforeTest() { driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("https://www.baidu.com"); } @AfterTest public void afterTest() { driver.quit(); } }