【问题标题】:Condition- assert using Selenium使用 Selenium 进行条件断言
【发布时间】:2015-05-22 05:20:48
【问题描述】:

我想编写一个脚本来检测此消息“系统没有响应您的请求。请稍后再试。”如下面的屏幕截图所示。当此消息出现时,我想验证并向开发团队发送邮件。

我为验证目的而编写的片段,但对我来说效果不佳,请提出一些替代方案:

String s1 = d1.findElementByXPath(".//*[@id='showSearchResultDiv']").getText();
        System.out.println(s1);

【问题讨论】:

  • 请检查div元素是否在frame/iframe下。看看你的代码,它似乎你误会隐式等待与 Thread.sleep...

标签: selenium selenium-webdriver webdriver assertions browser-automation


【解决方案1】:

记住在编写自动化代码时要小心。如果场景并不总是出现,则不能尝试查找 XPath,因为如果对象(基于 XPath)首先不存在,则无法 getText()。您可能需要围绕您的代码进行 try/catch,然后将 println 放入 try 中。这种情况会经常发生,因此您可能希望在 WebDriver 之上编写自己的框架来处理这些用例。

如果这不是问题。在未能捕获异常的代码周围放置一个 try/catch。

【讨论】:

  • 系统没有响应您的请求。请稍后再试。
  • 我得到了这个 sn-p,但它不适用于 webdriver try { assertTrue( d1.("系统没有响应您的请求。请稍后再试。")); System.out.println("结果失败"); } catch (Throwable e) { System.out.println("结果通过"); }
  • d1 存在吗?也许它在到达那条线之前就失败了。 WebDriver 有时会在它自己的框架中崩溃,因此您可能需要查看内部异常。我会尝试在设置 d1 时或之前将 try/catch 块放在代码的前面。
【解决方案2】:

在检查其文本之前,您应该尝试等待您的元素出现:

for (int second = 0;; second++) {
    if (second >= 60) fail("timeout");
    try { if (d1.findElementByXPath(".//*[@id='showSearchResultDiv']").isDisplayed()) break; } catch (Exception e) {}
    Thread.sleep(1000);
}
String s1 = d1.findElementByXPath(".//*[@id='showSearchResultDiv']").getText();
System.out.println(s1);

确切的代码可能会有所不同,具体取决于您正在测试的网页(例如,如果元素每次都不会出现,则应删除“失败”行。

【讨论】:

  • try{ String bodyText = d1.findElementByXPath(".//*[@id='showSearchResultDiv']").getText(); if(bodyText.contains("系统没有响应")) {System.out.println("fail");} } catch(Exception e) {System.out.println(e);} //这样好吗
  • try{ String bodyText = d1.findElementByXPath(".//*[@id='showSearchResultDiv']").getText(); System.out.println("test2"); System.out.println(bodyText.contains("系统没有响应")); if(bodyText.contains("系统没有响应")) {System.out.println("失败"); System.out.println("test4");} System.out.println("test3");} catch(Exception e) {System.out.println(e);}
  • 在此代码中: System.out.println(bodyText.contains("系统没有响应")); //状态失败
猜你喜欢
  • 2016-07-16
  • 2014-07-03
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多