selenium java 封装
1、简单介绍
1)展示如何封装selenium的api,使其符合我们的使用需求;
2)展示如何使用page object模式写selenium脚本;
3)展示如何即时查找元素,用以操作ajax页面;
2、封装selenium的api
以下是BasePage.java的代码;
用于展示方法,所以只封装了部分selenium的api;
1 package com.ddg.fundstransfer.tools; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 7 import java.util.concurrent.TimeUnit; 8 9 /** 10 * Created by Terry on 2017/9/27. 11 */ 12 public class BasePage { 13 WebDriver driver; 14 WebElement element; 15 public BasePage(WebDriver driver){ 16 this.driver=driver; 17 this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 18 } 19 public WebDriver getDriver(){ 20 return this.driver; 21 } 22 public WebElement findElement(CustomLocator locator){ 23 if(locator.type.equals("css")) { 24 this.element = driver.findElement(By.cssSelector(locator.value)); 25 } 26 return element; 27 } 28 public String getTitle(){ 29 return this.driver.getTitle(); 30 } 31 public void quit(){ 32 this.driver.quit(); 33 } 34 }
3、应用page object模式和即时查找元素;
1 package com.ddg.fundstransfer.pages; 2 3 import com.ddg.fundstransfer.tools.BasePage; 4 import com.ddg.fundstransfer.tools.CustomLocator; 5 import org.openqa.selenium.WebDriver; 6 7 /** 8 * Created by Terry on 2017/9/27. 9 */ 10 public class BaiduHomePage extends BasePage { 11 String url = "https://www.baidu.com/"; 12 CustomLocator userInput = new CustomLocator("css", "#kw"); 13 CustomLocator searchBtn = new CustomLocator("css", "#su"); 14 15 public BaiduHomePage(WebDriver driver){ 16 super(driver); 17 super.getDriver().get(this.url); 18 super.getDriver().manage().window().maximize(); 19 } 20 21 public void Search(String keyword){ 22 super.findElement(userInput).sendKeys(keyword); 23 super.findElement(searchBtn).click(); 24 } 25 }
4、测试脚本
1 package com.ddg.fundstransfer.tests; 2 3 import com.ddg.fundstransfer.pages.BaiduHomePage; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.chrome.ChromeDriver; 6 import org.testng.annotations.AfterTest; 7 import org.testng.annotations.BeforeTest; 8 import org.testng.annotations.Test; 9 10 /** 11 * Created by Terry on 2017/9/27. 12 */ 13 public class TestBaiduHomePage { 14 WebDriver driver; 15 BaiduHomePage baiduPage; 16 @BeforeTest 17 public void setup(){ 18 driver = new ChromeDriver(); 19 baiduPage = new BaiduHomePage(driver); 20 } 21 @AfterTest 22 public void teardonw(){ 23 driver.quit(); 24 } 25 26 @Test 27 public void testBaiduHomePage(){ 28 baiduPage.Search("china"); 29 System.out.print(baiduPage.getTitle()); 30 } 31 32 }