c# - Selenium C# 查找警报并验证文本

标签 c# selenium

我正在寻找一个示例来验证是否发生了 JavaScript 警报。我有一个进入登录页面并尝试登录系统的脚本。我有一个成功登录的测试用例,并且正在尝试处理失败的登录用例。任何有关自动化最佳实践的建议将不胜感激。因此,归根结底,我的问题很简单:“如何验证此警报是否发生在我的网页上?”

HTML

<div class="alert">
The username and/or password entered are invalid.</div>

测试

    [Test]
    public void failedCustomerLogin()
    {
        //Finding the customer login link and clicking it
        var customerLogin = driver.FindElement(By.Id("Homepage_r2_c14"));
        customerLogin.Click();

        Assert.AreEqual("http://stage.blank.net/login", driver.Url);

        var userName = driver.FindElement(By.Id("username"));
        userName.SendKeys("badCustomerName");

        var Pasw = driver.FindElement(By.Id("password"));
        Pasw.SendKeys("BadPassword");

        var submit = driver.FindElement(By.Id("btnSubmit"));
        submit.Click();

        //TODO: need to find failed method
        string errorText = driver.SwitchTo().Alert().Text;
        Assert.IsTrue(errorText.Contains("The username and/or password entered are invalid."));
    }

等等 Selenium

        //Waiting for error to display
        driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));

最佳答案

尝试以下操作并断言预期文本是否存在,具体取决于您使用的测试框架和断言。

string text = Driver.SwitchTo().Alert().Text;

我使用NUnit断言,在我的例子中它看起来像下面

string text = Driver.SwitchTo().Alert().Text;

Assert.IsTrue(text.Contains("The username and/or password entered are invalid."));

第二次编辑:添加显式等待

尝试添加显式等待

Driver.FindElement(By.TagName("test")).Click();

//Make sure the click above generates the alert
String text = (new WebDriverWait(Driver, TimeSpan.FromSeconds(10))).Until(d => d.SwitchTo().Alert().Text);
Assert.IsTrue(text.Contains("The username and/or password entered are invalid."));

关于c# - Selenium C# 查找警报并验证文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565643/

相关文章:

c# - 创建枚举后销毁 EnumBuilder?

c# - 确定 html 节点的样式

c# - 在不转换本地时间的情况下在c#中获取东部时间

多步 iframe 中的 Selenium (paypal)

java - Selenium 2 : Webdriver : How to create my custom wrapper class for selenium components?

java - 显示时使用 XPath 排除不可见元素 : none; is set in CSS class?

java - 如何同时打开浏览器和android并同时运行测试?

c# - 使用 QueryString 跟踪 Turn

c# - 亚马逊 s3 存储桶可以用于队列吗?

c# - Entity Framework Scaffold-DbContext 用户登录失败