C# isElementPresent带有Selenium Webdriver的自定义错误消息字符串

C# isElementPresent带有Selenium Webdriver的自定义错误消息字符串,c#,visual-studio,selenium-webdriver,C#,Visual Studio,Selenium Webdriver,我最近在visual studio中安装了Selenium Webdriver,我正在尝试创建一个函数来检查isElementPresent,其中包含一条自定义错误消息,作为基于此处建议的参数: 目前我的脚本看起来像 private bool isElementPresent(By by, string Message) { try { driver.FindElement(by); ; return tru

我最近在visual studio中安装了Selenium Webdriver,我正在尝试创建一个函数来检查isElementPresent,其中包含一条自定义错误消息,作为基于此处建议的参数:

目前我的脚本看起来像

private bool isElementPresent(By by, string Message)
    {
        try
        {
            driver.FindElement(by); ;
            return true;
        }
        catch (NoSuchElementException e)
        {
            System.Diagnostics.Debug.WriteLine(Message);
            return false;
        }
    }
private bool isElementPresent(By locator)
{
    return Driver.FindElements(locator).Any();
}

有人知道如何处理这个问题吗?

我的建议是不要在函数中混合验证。使用NUnit断言验证布尔返回

您的代码实际上没有使用您引用的链接中建议的方法。应该是这样的

private bool isElementPresent(By by, string Message)
    {
        try
        {
            driver.FindElement(by); ;
            return true;
        }
        catch (NoSuchElementException e)
        {
            System.Diagnostics.Debug.WriteLine(Message);
            return false;
        }
    }
private bool isElementPresent(By locator)
{
    return Driver.FindElements(locator).Any();
}
被称为

Assert.IsTrue(isElementPresent(By.Id("login")), "Verify login button is present");

注意:您可能需要使用System.Linq;,添加Linq引用;,为了使用.Any.

-“System.Collections.ObjectModel.ReadOnlyCollection”不包含接受类型为“System.Collections.ObjectModel.ReadOnlyCollection”的第一个参数的“Any”定义,可以找到它。您是否缺少using指令或程序集引用?-出于某些原因,Any似乎反应不正确,我不知道当然知道原因。我不知道您是否正在使用Visual Studio,但如果您将鼠标悬停在任何位置上,它应该有一个红色的波形,请单击“显示潜在修复”,然后使用System.Linq;添加;。您缺少的参考资料是Linq。如果此答案或任何答案有用,请向上投票。如果它回答了你的问题,请接受它作为答案,这样它就不会被认为没有答案。