其实如果大家有途径的话已经可以在StackOverflow上找到数不尽的解决办法了。
大部分解决办法可能都会推荐代码刷新界面然后在测一遍,或者写个for/while loop 来多找几次,或者是.pollingEvery()
那么当遇到一些限制导致不能依靠刷新界面来重新测试的时候,我个人找到了一个旁门左道的办法 :D
今天分享一下在开发Selenium + Cucumber + NGTest 的Maven project,在Azure DevOps上运行nightly automation test的时候遇到了很严重的 Stale Element Reference解决办法
(着重强调是在Azure上面才会遇到的问题,是因为这个问题在本地跑的时候完全没有问题且无法复现)
因为我用的是cucumber框架,所以在StepDefinition.java里面写的都是elements xpaths。那么一般我们都会这样定位一个element,之后在另一个java文件里直接调用:
@FindBy(xpath = "//button[@data-qa='button-enter']")
public WebElement enterButton;
但是如果遇到stale element reference问题严重的,重复的出现在一个element上的时候,我们可以直接在StepDefinition里把这个element的xpath换写成function:
public WebElement enterButton()
{
By by = By.xpath("//button[@data-qa='button-enter']");
WebDriverWait waiter = new WebDriverWait(driver, 5000);
waiter.ignoring(NoSuchElementException.class);
waiter.until(ExpectedConditions.visibilityOfElementLocated(by));
waiter.until(ExpectedConditions.elementToBeClickable(by));
return driver.findElement(by);
};
在等待element出现前用WebDriverWait.ignoring忽视掉NoSuchElementException.class 错误,继续定位该element
看着生猛还管用的一小段代码,请诸位笑纳
如果xpath太多的话,其实不推荐都改成这个function
一小段生猛代码看着合理,一堆放在一起,头皮发麻