本博文主要介绍自动化测试中,无论是selenium或是Appium的四种等待方式,合理的使用等待对代码的稳定性,测试效率都有很大的提高
隐式等待:是在尝试发现某个元素的时候,如果没能立刻发现,就等待固定长度的时间。默认设置是0秒。一旦设置了隐式等待时间,它的作用范围就是Webdriver对象实例的整个生命周期
显示等待:定义了等待条件,只有该条件触发,才执行后续代码。
强制等待:指定了固定的等待时长,单位秒
Fluent Wait:他是显示等待的一种,他允许我们定义轮询间隔、忽略某种异常、超时时间等
二、实例代码
// Java
/*
* @FileName Wait_Demo:
* @author davieyang
* @create 2018-11-29 14:10
*/
package testscript;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.*;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.AfterClass;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.*;
import org.testng.annotations.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Listeners({util.TestReport.class})
public class Wait_Demo {
AndroidDriver driver;
static {
//指定log4j配置文件为log4j.xml
DOMConfigurator.configure("log4j.xml");
}
@BeforeClass
public void setUp()throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
// des.setCapability("app", "c:\\");
caps.setCapability("automationname", "Appium");
caps.setCapability("platformName", "Android");
caps.setCapability("platformVersion", "23");
caps.setCapability("udid", "WTKDU17105005171");
caps.setCapability("deviceName", "Honor");
caps.setCapability("appPackage", "com.tencent.Q108");//com.android.contacts
caps.setCapability("appActivity", "com.tencent.Q108.SplashActivity");//.activities.PeopleActivity
caps.setCapability("appWaitActivity", "com.tencent.Q108.SplashActivity");
caps.setCapability("unicodeKeyboard", "True");
caps.setCapability("resetKeyboard", "True");
caps.setCapability("newCommandTimeout", "15");
caps.setCapability("nosign", "True");
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"),caps);
//隐式等待
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void test_() {
// 强制等待
Thread.sleep(10);
// 显式等待
WebDriverWait explicitwait = new WebDriverWait(driver, 10);
explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("text1")));
// 流畅等待
FluentWait fluentwait = new FluentWait(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(250, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(TimeoutException.class);
fluentwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("text1")));
}
@AfterClass
public void tearDown() {
driver.closeApp();
}
}