網站自動化測試處理 Alert的幾個程式實作技巧

網站自動化測試處理 Alert的幾個程式實作技巧

這篇文章主要說明Alert處理的三個技巧。Alert經常出現在網站特別需要提醒的狀況。

如果自動化測試不特別處理的話,Alert的出現常導致自動化測試失敗。

因此,對於自動化測試來說,需要處理的主要有三個狀況,

Alert是否存在,取得Alert上面的文字,點擊Alert的 OK.

這篇文章針對這三種狀況說明與舉出程式範例。

 

如何確定Alert是否存在

[pastacode lang=”java” message=”” highlight=”” provider=”manual”]

public boolean validateAlertPresent() {
	try{
		new WebDriverWait(driver, 15).until(ExpectedConditions.alertIsPresent());
	}catch(RuntimeException e){
		return false;
	}
	return true;
}

[/pastacode]

 

如何取得 Alert上面的文字

[pastacode lang=”java” message=”” highlight=”” provider=”manual”]

protected String getAlertText() {
	// Get a handle to the open alert, prompt or confirmation
	Alert alert = driver.getDriver().switchTo().alert();
	// Get the text of the alert or prompt
	return alert.getText();
}

[/pastacode]

 

如何點擊 Alert並印出Alert文字

[pastacode lang=”java” message=”” highlight=”” provider=”manual”]

public void clickOkInAlert() {
	Assert.assertTrue(validateAlertPresent(), "The alert is not present");
	// Get a handle to the open alert, prompt or confirmation
	Alert alert = driver.getDriver().switchTo().alert();
	// Get the text of the alert or prompt
	System.out.println("alert: " + alert.getText());
	// And acknowledge the alert (equivalent to clicking "OK")
	alert.accept();
}

[/pastacode]

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *