Selenium Webdriver:处理NoSuchElementException的最佳实践 [英] Selenium Webdriver: best practice to handle a NoSuchElementException

查看:956
本文介绍了Selenium Webdriver:处理NoSuchElementException的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过多次搜索和阅读后,我仍然不清楚使用Webdriver处理失败断言的最佳方法。我原以为这是一个常见的核心功能。我想做的就是:




  • 寻找一个元素

  • 如果有的话 - 告诉我

  • 如果不存在 - 告诉我



我想向非技术受众展示结果,所以让它用完整的堆栈跟踪抛出'NoSuchElementExceptions'是没有用的。我只是想要一个好消息。



我的测试:

  @测试
public void isMyElementPresent(){
// WebElement myElement driver.findElement(By.cssSelector(#myElement));
if(driver.findElement(By.cssSelector(#myElement))!= null){
System.out.println(我的元素在页面上找到);
} else {
System.out.println(页面上找不到我的元素);
}
}

当我强制失败时,我仍然会收到NoSuchElementException 。我还需要试一试吗?我可以在不需要System.out.println的情况下合并Junit断言和/或Hamcrest来生成更有意义的消息吗?

解决方案

我遇到过类似的情况。根据 Javadoc findElement findElements API,似乎 findElement 行为是设计使然。您应该使用 findElements 来检查不存在的元素。



因为在你的情况下,WebElement可能不存在,你应该使用 findElements 。 / p>

我会按如下方式使用它。

  List< WebElement> elems = driver.findElements(By.cssSelector(#myElement)); 
if(elems.size == 0){
System.out.println(我的元素未在页面上找到);
} else
System.out.println(我的元素在页面上找到);
}


After much searching and reading, I'm still unclear as to the best way to handle a failed assertion using Webdriver. I would have thought this was a common and core piece of functionality. All I want to do is:

  • look for an element
  • if present - tell me
  • if not present - tell me

I want to present the results for a non technical audience, so having it throw 'NoSuchElementExceptions' with a full stack trace is not helpful. I simply want a nice message.

My test:

@Test
public void isMyElementPresent(){
  //  WebElement myElement driver.findElement(By.cssSelector("#myElement"));
    if(driver.findElement(By.cssSelector("#myElement"))!=null){
        System.out.println("My element was found on the page");
    }else{
            System.out.println("My Element was not found on the page");
        }
    }

I still get a NoSuchElementException thrown when I force a fail. Do I need a try/catch as well? Can I incorporate Junit assertions and/or Hamcrest to generate a more meaningful message without the need for a System.out.println?

解决方案

I have encountered similar situations. According to the Javadoc for the findElement and findElements APIs, it appears that the findElement behavior is by design. You should use findElements to check for non-present elements.

Since in your case, there's a chance that the WebElement is not present, you should use findElements instead.

I'd use this as follows.

List<WebElement> elems = driver.findElements(By.cssSelector("#myElement"));
if (elems.size == 0) {
        System.out.println("My element was not found on the page");
} else
        System.out.println("My element was found on the page");
}

这篇关于Selenium Webdriver:处理NoSuchElementException的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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