要添加到@雅立的回答,我已經提出了一些擴展方法有助於消除競爭條件。
這是我的設置:
我有一個叫做「Driver.cs」的類。它包含一個充滿驅動程序擴展方法和其他有用靜態函數的靜態類。
對於元素我通常需要檢索,我創建像一個擴展方法如下:
public static IWebElement SpecificElementToGet(this IWebDriver driver) {
return driver.FindElement(By.SomeSelector("SelectorText"));
}
這可以讓你從任何測試類檢索元素與代碼:
driver.SpecificElementToGet();
現在,如果這導致StaleElementReferenceException
,我在我的驅動程序類中有以下靜態方法:
public static void WaitForDisplayed(Func<IWebElement> getWebElement, int timeOut)
{
for (int second = 0; ; second++)
{
if (second >= timeOut) Assert.Fail("timeout");
try
{
if (getWebElement().Displayed) break;
}
catch (Exception)
{ }
Thread.Sleep(1000);
}
}
該函數的第一個參數是返回IWebElement對象的任何函數。第二個參數是以秒爲單位的超時(超時代碼是從Selenium IDE for FireFox中複製的)。該代碼可以用於避免陳舊元件例外以下方式:
MyTestDriver.WaitForDisplayed(driver.SpecificElementToGet,5);
上面的代碼將調用driver.SpecificElementToGet().Displayed
直到driver.SpecificElementToGet()
沒有拋出異常和.Displayed
評估爲true
5秒沒有通過。 5秒後,測試將失敗。
在另一面,等待一個元素不存在,你可以使用下面的函數一樣:
public static void WaitForNotPresent(Func<IWebElement> getWebElement, int timeOut) {
for (int second = 0;; second++) {
if (second >= timeOut) Assert.Fail("timeout");
try
{
if (!getWebElement().Displayed) break;
}
catch (ElementNotVisibleException) { break; }
catch (NoSuchElementException) { break; }
catch (StaleElementReferenceException) { break; }
catch (Exception)
{ }
Thread.Sleep(1000);
}
}
希望17k的意見表明,它不只是你;)這已成爲最令人沮喪的Selenium例外。 – 2013-06-12 04:45:49
48k吧!我有同樣的問題... – Gal 2015-06-25 04:22:09
我發現硒是純粹的,完整的垃圾.... – 2015-10-29 20:44:05