WebDriver拾级而上(10) – 封装与重用

webdriversjes

WebDriver对页面的操作,需要找到一个WebElement,然后再对其进行操作,比较繁琐:

// Find the text inputelement by its name
WebElement element = driver.findElement(By.name("q"));

// Enter something to search for
element.sendKeys("Cheese!");


我们可以考虑对这些基本的操作进行一个封装,简化操作。比如,封装代码:

protected void sendKeys(By by, String value){
   driver.findElement(by).sendKeys(value);
}

那么,在测试用例可以这样简化调用:

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

看,这就简洁多了。

类似的封装还有:

package com.drutt.mm.end2end.actions;
 
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.drutt.mm.end2end.data.TestConstant;
 
public class WebDriverAction {
	//protected WebDriverdriver;
	protected RemoteWebDriverdriver;
	protected WebDriverWaitdriverWait;


	protected boolean isWebElementExist(By selector) { 
		try { 
			driver.findElement(selector);
			return true;     
		} catch(NoSuchElementException e) { 
			return false; 
		} 
	} 
    
    protected String getWebText(By by) { 
        try { 
			return driver.findElement(by).getText();
        } catch (NoSuchElementException e) { 
            return "Textnot existed!"; 
        } 
    } 
    
    protected void clickElementContainingText(By by, String text){
        List<WebElement>elementList = driver.findElements(by);
        for(WebElement e:elementList){
            if(e.getText().contains(text)){
                e.click();
                break;
            }
        }     
    }
    
    protected String getLinkUrlContainingText(By by, String text){
        List<WebElement>subscribeButton = driver.findElements(by);
        String url = null;
        for(WebElement e:subscribeButton){
            if(e.getText().contains(text)){
                url =e.getAttribute("href");
                break;
            }
        }
        return url;
    }
    
    protected void click(By by){
       driver.findElement(by).click();
       driver.manage().timeouts().implicitlyWait(TestConstant.WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS); 
    }
 
    protected String getLinkUrl(By by){
        return driver.findElement(by).getAttribute("href");
    }
    
    protected void sendKeys(By by, String value){
       driver.findElement(by).sendKeys(value);
    }
}

[转自网络(如知原出处,请留言告知)]

发表评论

邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据