Selenium assertFalse 因 staleelementreferenceexception 而失败 [英] Selenium assertFalse fails with staleelementreferenceexception

查看:37
本文介绍了Selenium assertFalse 因 staleelementreferenceexception 而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a selenium test in Java and I am doing some assertions like that:

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

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

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

It´s the standard method Selenium is generating when export from IDE to Java Webdriver.

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

(Yes I want to assert that this element is not present)

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

I always get errors when I am testing at this above code line Error: stale element reference: element is not attached to the DOM

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

But when I put a thread.sleep in front of that step it works. The fact I don´t get is that it is enough to wait 1 milli sec. Is it typical to wait before an assertion? Is there another way to solve this? (Implicit wait is not helping here) Greetings from Germany!

推荐答案

当你在 assertFalse() 函数中面临 staleelementreferenceexception 时,要否定 FalsePossitive 用例,您可以使用 ExpectedConditions 子句设置为 stalenessOf 如下:

As you are facing staleelementreferenceexception in assertFalse() function, to negate the FalsePossitive usecase you can induce WebDriverWait with ExpectedConditions clause set to stalenessOf within assertTrue() function as follows :

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.

Explaination

The ExpectedConditions clause stalenessOf will check for the staleness of the element identified as (By.xpath("//td[2]/div")). When the intended element becomes stale, you can check for assertTrue(boolean condition). assertTrue() would assert that a condition is true. If it isn't, an AssertionError would be raised.

如果您仍想实现 assertFalse 的 FalsePossitive 情况(condition) 引发 Error 你仍然可以:

If you still want to implement the FalsePossitive case of assertFalse(condition) raising Error you still can :

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

这篇关于Selenium assertFalse 因 staleelementreferenceexception 而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆