【问题标题】:How to fail the test if required field error message is displayed in c#?如果 c# 中显示必填字段错误消息,如何使测试失败?
【发布时间】:2023-04-08 08:49:01
【问题描述】:

我是测试环境的新手。有一个基本的表格,如姓名、地址等。当我点击保存按钮并显示必填字段错误消息时,如何测试失败?我能够使用 XPath 找到错误消息。这是我尝试过的代码,但反过来。当显示错误消息时,我尝试过的代码通过了测试。如果显示错误消息,请告知测试失败的方法。

 try
        {
            //Clear the value of first name
            IWebElement firstname = driver.FindElement(By.Id("FirstName"));
            firstname.Clear();

            //Click on save button
            IWebElement save_profile = driver.FindElement(By.XPath("//div[@class='form-group buttons']/div/input"));
            save_profile.Click();

            //Locate Error Message and Compare the text wit the displayed error message.
            IWebElement FirstNameError = driver.FindElement(By.XPath("//form[@class='default form-horizontal']/fieldset/div[4]/div[2]/span/div"));
            Assert.AreEqual("Please, enter 'First Name'.", FirstNameError.Text);
        }

        catch
        {
            //Fails the test if error message is not displayed
            Assert.Fail();
        }

如果找到元素,有什么方法可以使测试失败?提前致谢。

【问题讨论】:

    标签: c# unit-testing selenium-webdriver


    【解决方案1】:

    如果元素不应该存在:

    Assert.IsNull(FirstNameError);
    

    如果元素存在,但不包含错误信息:

    Assert.IsTrue(String.IsNullOrEmpty(FirstNameError.Text));
    

    因为 XPath 非常具体,所以这些解决方案有点脆弱,如果您的布局稍有变化,您将不得不调整您的 XPath 表达式。

    为了适应这种情况,您可以稍微调整您的逻辑,例如:

    IWebElement FirstNameError = driver.FindElement(
        By.XPath("//form[@class='default form-horizontal']/fieldset//div[contains(text(), \"Please, enter 'First Name'.\")]"));
    
    Assert.IsNull(FirstNameError);
    

    所以,这里我们基本上是说,如果在指定表单的字段集中的任何地方有一个 div 元素包含文本“请输入 'First Name'”,则测试将失败。

    这样做,您显然会引入一种新形式的脆弱性。如果您的错误消息发生更改,您的测试将不再有效。解决这个问题的方法是定义一些您在 UI 和测试用例中使用的共享常量/消息。

    【讨论】:

    • String.IsNullOrEmpty()断言会更好
    • @RoberHarvey 取决于元素是否存在。
    • 你真的要考虑一下吗?无论如何,空字符串也可能没有错误,因为您没有。
    • @RoberHarvey 这不是我想考虑的问题,而是获得null 元素的Text 属性会给我一个NPE,不是吗?
    • 如果FirstNameError 是实时表单中的文本框,则它永远不会为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多