Selenium assertFalse失败,并带有staleelementreferenceException [英] Selenium assertFalse fails with staleelementreferenceexception

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

问题描述

我用Java进行了硒测试,并且正在做这样的断言:

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; }

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

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 时,否定

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(condition) 提出错误,您仍然可以:

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天全站免登陆