1. 程式人生 > >Selenium+TestNG Web自動化測試環境搭建6_selenium中的等待

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);