Selenium+TestNG Web自动化测试环境搭建6_selenium中的等待

Web页面是一个逐步加载的过程。当元素没有加载完时,我们对其操作将会失败。

因此,要保证web测试的稳定性,等待处理必不可少。


Selenium的等待可以分为两类:显示等待(Explicit Waits)和隐式等待(Implicit Waits)。

1)显式等待:

在执行某一个操作之前,明确给定一个等待时间,又可以分为静态等待和动态等待;

静态等待:如Thread.sleep(4000);   //等待4秒

除非你能确定某一个场景的等待时间,否则应该减少此种用法,特别是在公共方法里面。

因为页面加载是动态的,当网络不的好时候,等待时间设置少了会导致用例执行失败;而过多的固定等待会引起时间的浪费。

特别是测试用例很多,测试版本不稳定的时候。

动态等待:我们用WebDriverWaitExpectedCondition相结合来实现动态的等待

	public WebElement ImplicitWait(final String xpath) {
		WebDriverWait wait = new WebDriverWait(driver, 30);
		WebElement webelement = wait.until(new ExpectedCondition<WebElement>() {
			public WebElement apply(WebDriver d) {
				return d.findElement(By.xpath(xpath));
			}
		});
		return webelement;
	}

实现过程: 将wait超时时间设成30秒(超过这个时间会报 TimeoutException),否则webdriver每500ms会轮询一次,直到ExpectedCondition返回成功。

      一旦ExpectedCondition返回成功,等待就会停止,因此是一个动态的等待过程;

其他例子:(主要是基于ExpectedConditions的API来封装):

	public WebElement waitElementPresent(String xpath) {
		WebDriverWait wait = new WebDriverWait(driver, 30);
		WebElement webelement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
		return webelement;
	}

	public boolean isElementVisiable(String xpath) {
		WebDriverWait wait = new WebDriverWait(driver, 30);
		Boolean isElementVisiable = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(xpath)));
		return isElementVisiable;
	}
不多写,大家自行根据 ExpectedConditions 的API进行封装即可。


2)隐式等待:
为了防止元素不可用,让webdriver轮询一段时间。它也是一种动态的等待。
	public WebElement isElementVisiable(String xpath) {
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		driver.get("http://www.baidu.com");
		WebElement webelement = driver.findElement(By.xpath(xpath));
		return webelement;
	}

补充一些其他的等待:
页面加载超时:
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
脚本执行超时:
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值