常用类抽取
通过之前方式也能进行测试脚本的实现,但效率不高,测试框架的作用就是为了提高后续脚本的编写效率而进行的一系列的抽取、封装、优化等操作。
现在可以新建一个包,比如较common,用来存放一些通用的类,然后在这个包下新建一个类Helper,在这个列里对常用的定位方式和操作进行封装,这样后续进行控件定位或者操作就会比较方便,不用卸太长的代码,后续如果要对某个操作的方法进行改动的话也只需要来这个类对应的方法进行修改而无需去调用到的地方处处修改。封装完后的测试代码如下(每个方法是干嘛的都有添加对应的注释):
package appium.common;
import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.Set;
public class Helper {
private AppiumDriver driver;
//设置默认超时时间
private final long DEFAULT_TIMEOUT = 5;
private final long LONG_TIMEOUT = 10;
//通过构造方法来初始化AppiumDriver对象引用,这样才能获得Appium提供的方法
public Helper(AppiumDriver driver){
this.driver = driver;
}
//封装智能等待的方法,取代Thread.sleep(),这样可以节省时间,默认等待5秒
public void waitForElement(By by){
WebDriverWait wait = new WebDriverWait(driver,DEFAULT_TIMEOUT);
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
//如果需要等待比较长的时候可以调用这个方法
public void waitForElementForLongTime(By by){
WebDriverWait wait = new WebDriverWait(driver,LONG_TIMEOUT);
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
/**
* 封装常见定位方法
*/
//按id定位
public WebElement findById(String id){
waitForElement(By.id(id));
return driver.findElement(By.id(id));
}
//多个相同id的定位方法,index从0开始
public WebElement findById(String id, int index){
waitForElement(By.id(id));
return (WebElement) driver.findElements(By.id(id)).get(index - 1);
}
//按控件类型定位
public WebElement findByClassName(String cls