[英]How to write a code that will execute after each step is executed
我工作的應用程序拋出了很多意外警報。 我想通過一個常見的方法isAlert來實現一種捕獲所有這些的方法。
但是對於webdrriver中的每一步,如何調用isAlertpresnt,有人可以幫助我嗎?
通常我的方法是這樣的: -
public void checkAlert() {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//exception handling
}
}
問題是如何在每一步之前調用它? 我知道這會使我的代碼變慢但很難實現這個。
我正在尋找在我的測試中每個命令\\步之后執行的東西。這可能嗎?
目前我在所有預期的場景中使用try catch調用此方法。
WebDriver具有WebDriverEventListener
偵聽器,用於完成您要執行的操作。 通過實現此偵聽器並注冊驅動程序 - 您可以在使用webdriver執行的每個操作之前/之后,在幕后調用此checkAlert
方法。
看看這個例子。
通過使用事件監聽器,已經提供了一個很好的答案。
另一種簡單的處理方法,如果您使用關鍵字/方法進行所有selenium操作。 我想說的是,如果你使用click(“locator”)方法在你的測試用例中執行click而不是一次又一次地編寫驅動程序命令,那么你可以在點擊該click方法后插入那個alert cross checking命令。
public void myClick(String myxpath){
driver.findElement(By.xpath(myxpath)).click();
//calling checkAlert method to cross check
}
因此,如果您使用點擊,輸入等方法進行硒動作,那么您可以嘗試上述方法。
謝謝你,穆拉利
I could think of a solution using a Thread, which always monitors if there is any alert present, if yes then accept else don't do any thing. Considering you are using a testNG or Junit framework, here is the sample:
package poc.grid;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
public class Test {
static WebDriver driver;
//This method returns a Thread, which monitors any alert and accept whenever finds it. And this return a Thread object.
public static Thread handleAlert(final WebDriver driver)
{
Thread thread = new Thread(new Runnable() {
public void run() {
while(true)
{
try
{
System.out.println("Checking alert .... ");
driver.switchTo().alert().accept();
System.out.println("Alert Accepted. ");
}catch(NoAlertPresentException n){
System.out.println("No Alert Present. ");
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
}
});
return thread;
}
@BeforeTest
public void beforeTest()
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//In before Test, just call Thread and start it.
handleAlert(driver).start();
}
//This is your normal Test
@org.testng.annotations.Test
public static void test()
{
try
{
driver.get("https://payments.billdesk.com/pb/");
int i=0;
while(i<=10)
{
driver.findElement(By.xpath("//button[@id='go']")).click();
Thread.sleep(2000);
i++;
}
}catch(Exception e)
{
System.out.println("Exception: "+e.getMessage());
}
}
//At the end of test, you can stop the Thread.
@AfterTest
public void afterTest()
{
handleAlert(driver).stop();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.