[英]java : how to handle the design when template methods throw exception when overrided method not throw
[英]How to retry some methods several seconds, and when timeout throw the method's exception rather than TimeoutException in selenium?
我想將 select 元素設置為 select 一個選項。 但是頁面加載時該選項可能不存在。 因為選項是從數據庫加載的,API,或者有響應時間的東西。
目前,我使用 selenium wait.until 和 boolean 條件。 制作自定義等待方法。
我的解決方法:
.
.
.
String exceptionMessage;
public void myCode() throws Exception {
exceptionMessage = "";
Integer sec = 10;
WebDriverWait wait = new WebDriverWait(shared.getBrowser(), Duration.ofSeconds(sec));
try {
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
try {
.
.
.
CommonMethods.selectOption(element, optionText);
return true;
} catch (Exception e) {
exceptionMessage = e.getMessage();
return false;
}
}
});
} catch (TimeoutException e) {
throw new Exception("Timeout: [" + sec + "] seconds, Exception message: [" + exceptionMessage + "]");
}
}
如果超時,結果將是:
java.lang.Exception: Timeout: [10] seconds, Exception message: [element not visible: Element is not currently visible and may not be manipulated
有沒有 selenium 方法呢? 還是更好的方法?
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" xpath']")));
使用獨特的 Xpath 查找元素,因為會有一些隱藏元素。
如果上述等待不起作用,您也可以嘗試以下方法:
new WebDriverWait(Driver,TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible("Yyour element path");
我不認為你需要那么多。
我的 c# 比我的 java 好,但這是我會使用的那種結構。 我已經在 intellij 中運行它,它似乎可以工作 - 但我沒有你的操作和站點來測試它。
@Test
public void myCode() throws Exception {
exceptionMessage = "";
Integer sec = 10;
WebDriverWait wait = new WebDriverWait(driver, sec);
try {
wait.until((WebDriver dr) ->
{
try {
//Your actions go here
//this one will always fail - comment it out to make it pass
dr.findElement(By.tagName("I will fail you!")).click();
return true;
} catch (Exception e) {
exceptionMessage = e.getMessage();
return false;
}
});
} catch (TimeoutException e) {
throw new Exception("Timeout: [" + sec + "] seconds, Exception message: [" + exceptionMessage + "]");
}
System.out.println("The exception message is.... " + exceptionMessage);
}
我剛剛拋出了一個明顯的失敗元素。
沒有注釋:
dr.findElement(By.tagName("I will fail you!")).click();
它返回您的超時錯誤捕獲行。 我得到:
java.lang.Exception: Timeout: 1 seconds, Exception message: [no such element: Unable to locate element: {"method":"css selector","selector":"I\ will\ fail\ you:"} (會話信息。chrome=84.0.4147.105)
將其注釋掉 - 它在異常消息中不返回任何內容(因此返回 true,因此返回 pass):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.