【问题标题】:Ensure all 3 lines throw exception before returning true在返回 true 之前确保所有 3 行都抛出异常
【发布时间】:2020-07-07 07:21:14
【问题描述】:

为了让我的方法返回 true,我需要确保 3 个特定的行都抛出错误。

try
{
    // Wait until all three lines to throw exception
    Driver.FindElement(By.CssSelector(loadingTypesLock));
    return false;
}
catch 
{
    try
    {
        Driver.FindElement(By.CssSelector(loadingTypesLock_bg));
        return false;
    } 
    catch
    {
        try
        {
            Driver.FindElement(By.CssSelector(loadingTypesLock_img));
            return false;
        } 
        catch
        {
            return true;
        }
    }
}

最好的方法是什么?

【问题讨论】:

  • 我会添加一个变量,每当发生异常时,你就增加 1。最后检查变量是否 = 3 然后返回 true
  • 不要用异常控制程序流
  • 你不应该使用trycatch语句来控制你的程序的流程
  • @Hdot 您是否考虑过Polly's Fallback 策略将三个操作串联起来?

标签: c# .net selenium-webdriver exception try-catch


【解决方案1】:

使用异常来控制程序流程通常被认为是不好的做法。相反,为什么不使用 FindElements (Selenium docs) 方法返回一个元素列表,然后检查列表的长度?

类似这样的:

return (Driver.FindElements(By.CssSelector(loadingTypesLock)).Count == 0 &&
        Driver.FindElements(By.CssSelector(loadingTypesLock_bg)).Count == 0 &&
        Driver.FindElements(By.CssSelector(loadingTypesLock_img)).Count == 0);

如果所有三个方法返回的列表的计数都为零,那么上面将返回true,因此当它们中的任何一个都没有找到任何元素时。如果他们中的任何一个找到一个元素,它将返回false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多