1. 程式人生 > >Selenium方法封裝

Selenium方法封裝

.net bar ron test sdn spa ref java 需要

Selenium 封裝

Selenium 封裝

WebDriver對頁面的操作,需要找到一個WebElement,然後再對其進行操作,比較繁瑣:

[java] view plain copy
  1. WebElement element =driver.findElement(By.name("q"));
  2. element.sendKeys("Cheese!");

我們可以考慮對這些基本的操作進行一個封裝,簡化操作。比如,封裝代碼:

[java] view plain copy
  1. protected void sendKeys(By by, String value){
  2. driver.findElement(by).sendKeys(value);
  3. }

那麽,在測試用例可以這樣調用:

sendKeys(By.name("q"),”Cheese!”);

類似的封裝還有:

[java] view plain copy
  1. import java.util.List;
  2. import java.util.NoSuchElementException;
  3. import java.util.concurrent.TimeUnit;
  4. import org.openqa.selenium.By;
  5. import org.openqa.selenium.WebElement;
  6. import org.openqa.selenium.remote.RemoteWebDriver;
  7. import org.openqa.selenium.support.ui.WebDriverWait;
  8. public class DriverAction {
  9. protected RemoteWebDriver driver;
  10. protected WebDriverWait driverWait;
  11. private int WAIT_ELEMENT_TO_LOAD=10;
  12. protected boolean isWebElementExist(By selector) {
  13. try {
  14. driver.findElement(selector);
  15. return true;
  16. } catch(NoSuchElementException e) {
  17. return false;
  18. }
  19. }
  20. protected String getWebText(By by) {
  21. try {
  22. return driver.findElement(by).getText();
  23. } catch (NoSuchElementException e) {
  24. return "Text not existed!";
  25. }
  26. }
  27. protected void clickElementContainingText(By by, String text){
  28. List<WebElement>elementList = driver.findElements(by);
  29. for(WebElement e:elementList){
  30. if(e.getText().contains(text)){
  31. e.click();
  32. break;
  33. }
  34. }
  35. }
  36. protected String getLinkUrlContainingText(By by, String text){
  37. List<WebElement>subscribeButton = driver.findElements(by);
  38. String url = null;
  39. for(WebElement e:subscribeButton){
  40. if(e.getText().contains(text)){
  41. url =e.getAttribute("href");
  42. break;
  43. }
  44. }
  45. return url;
  46. }
  47. protected void click(By by){
  48. driver.findElement(by).click();
  49. driver.manage().timeouts().implicitlyWait(WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS);
  50. }
  51. protected String getLinkUrl(By by){
  52. return driver.findElement(by).getAttribute("href");
  53. }
  54. protected void sendKeys(By by, String value){
  55. driver.findElement(by).sendKeys(value);
  56. }
  57. }

Selenium方法封裝