【问题标题】:Selenium assertFalse fails with staleelementreferenceexceptionSelenium assertFalse 因 staleelementreferenceexception 而失败
【发布时间】:2018-08-20 06:18:40
【问题描述】:

我在 Java 中有一个 selenium 测试,我正在做一些这样的断言:

assertFalse(isElementPresent(By.xpath("//td[2]/div")));

private boolean isElementPresent(By by) {
try { driver.findElement(by); return true; }
catch (NoSuchElementException e) { 
return false; }

这是 Selenium 从 IDE 导出到 Java Webdriver 时生成的标准方法。

(是的,我想断言这个元素不存在)

当我在上面的代码行进行测试时,我总是会出错 错误:过时的元素引用:元素未附加到 DOM

但是当我在该步骤前面放置一个 thread.sleep 时,它可以工作。 我不明白的事实是等待 1 毫秒就足够了。 在断言之前等待是典型的吗? 还有其他方法可以解决这个问题吗? (隐式等待在这里没有帮助) 来自德国的问候!

【问题讨论】:

  • 分享isElementPresent()的代码
  • 不要添加评论,而是使用此附加信息更新实际问题以进行正确分析。

标签: selenium selenium-webdriver testng assertion staleelementreferenceexception


【解决方案1】:

当您在 assertFalse() 函数中面临 staleelementreferenceexception 时,要否定 FalsePossitive 用例,您可以通过将 ExpectedConditions 子句设置为 stalenessOf 来诱导 WebDriverWait assertTrue()函数如下:

Assert.assertTrue(new WebDriverWait(driver, 20).until(ExpectedConditions.stalenessOf(driver.findElement(By.xpath("//td[2]/div")))));

说明

ExpectedConditions 子句stalenessOf 将检查标识为(By.xpath("//td[2]/div")) 的元素的陈旧性。当预期元素变得陈旧时,您可以检查assertTrue(boolean condition)assertTrue() 会断言条件为真。如果不是,则会引发 AssertionError

assertFalse(条件)

如果您仍然想实现 assertFalse(condition) 引发 ErrorFalsePossitive 案例,您仍然可以:

Assert.assertFalse(new WebDriverWait(driver, 20).until(ExpectedConditions.stalenessOf(driver.findElement(By.xpath("//td[2]/div")))));

【讨论】:

  • 您好 DebanjanB,感谢您的回答。最后一个问题:我现在在 stalenessOf 表达式之后的“By”代码行中出现编译错误。 “ExpectedConditions 类型中的方法 stalenessOf(WebElement) 不适用于参数 (By)”所以我需要更改 isElementpresent 方法?
  • @ArnoDonCalzone 我的代码中有一个错误,我已更正,应该可以完美运行。让我知道状态。
  • 您好,感谢您的更新。效果很好。非常感谢!
【解决方案2】:

我认为,超时未设置为 WebDriver。试试这个

assertFalse(isElementPresent(By.xpath("//td[2]/div")));

private boolean isElementPresent(By by) {
driver.timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try { driver.findElement(by); return true; }
catch (NoSuchElementException e) { 
return false; }

【讨论】:

    猜你喜欢
    • 2014-10-13
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多