【问题标题】:How to verify that alert message is shown using Selenium in C#? [closed]如何验证在 C# 中使用 Selenium 显示的警报消息? [关闭]
【发布时间】:2019-12-28 14:33:35
【问题描述】:

我需要验证在网站中,当字段包含有效数据时,单击“保存”后会显示“信息已成功保存”的警报。现在我有一个代码来查找 web 元素并像这样填充有效数据:

IWebElement carName = driver.FindElement(By.XPath("..."));
carName.Click();
carName.SendKeys("Name of the car");

IWebElement saveButton = driver.FindElement(By.XPath("..."));
saveButton.Click();

我希望在显示消息时验证它已显示并且测试通过。

【问题讨论】:

  • 您需要解除的是 JS 警报还是 HTML 警报?如果您不确定,请触发警报,然后右键单击它。如果你什么也没得到,那可能是 JS 警报。如果您获得包含“检查”的常用上下文菜单,那么它就是 HTML。使用此信息更新您的问题。您的代码在哪里尝试访问此警报消息?你尝试了什么?您收到了哪些错误消息等。编辑您的问题并添加此信息。

标签: c# selenium testing selenium-webdriver


【解决方案1】:

判断弹出元素是否出现,如果不出现则元素计数为0

List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(driver.FindElements(By.XPath("..."));

if(elementList.Count > 0)
{
 //If the count is greater than 0 your element exists.
     Console.Write("pop up is present");
}else{
  Console.Write("pop up not present");
}

注意:请务必使用FindElements() 而不是FindElement()

【讨论】:

  • @watchstars - 你刚刚删除了我的接受答案,任何问题..注意你不能接受所有的答案,你需要接受一个适合你的答案
  • 虽然我可以同时选择它们,因为它们都对我有用。我现在该怎么办?
  • 选择您正在使用并感觉对您有用的一个以及所有答案中的最佳答案
【解决方案2】:

我建议使用 webdriverwait,因为根据表单的不同,成功消息之前可能会有延迟。

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
var element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("your xpath here")));
Assert.NotNull(element);

断言格式会因您的框架而异。那个来自 xUnit。

注意:没有维护包含 ExpectedConditions 的包,但它们非常简单,如果您担心,可以将其复制到您的代码或自己的包中。

public static Func<IWebDriver, IWebElement> ElementIsVisible(By locator)
{
    return (driver) =>
    {
        try
        {
            return ElementIfVisible(driver.FindElement(locator));
        }
        catch (StaleElementReferenceException)
        {
            return null;
        }
    };
}

private static IWebElement ElementIfVisible(IWebElement element)
{
    return element.Displayed ? element : null;
}

【讨论】:

  • 感谢您的帮助!当我尝试代码'ElementIsVisible'带有红色下划线时,它说:“'object'不包含'ElementIsVisible'的定义,并且找不到接受'object'类型的第一个参数的扩展方法'ElementIsVisible'(你是缺少 using 指令或程序集引用?”)。
  • expectedconditions 包含在单独的 nuget 包中。 dotnetseleniumextras.waithelpers
猜你喜欢
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多