如果c#中显示必填字段错误消息,如何使测试失败?

如果c#中显示必填字段错误消息,如何使测试失败?,c#,unit-testing,selenium-webdriver,C#,Unit Testing,Selenium Webdriver,我是测试环境的新手。有一个基本的表单,如姓名、地址等。当我点击保存按钮并显示必填字段错误消息时,如何使测试失败?我能够使用XPath定位错误消息。这是我试过的代码,但情况正好相反。当显示错误消息时,我尝试的代码通过了测试。如果显示错误消息,请建议如何使测试失败 try { //Clear the value of first name IWebElement firstname = driver.FindElement(By.Id

我是测试环境的新手。有一个基本的表单,如姓名、地址等。当我点击保存按钮并显示必填字段错误消息时,如何使测试失败?我能够使用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();
        }

如果发现元素,有没有办法使测试失败?提前感谢。

如果元素不存在:

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
元素包含文本“Please,enter'First Name”,测试就会失败


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

最好根据
字符串进行断言。IsNullOrEmpty()
@RoberHarvey取决于元素是否存在。您真的想考虑一下吗?空字符串也可能没有错误,因为您没有。@RoberHarvey我不想考虑它,但是获取
null
元素的
Text
属性会给我一个NPE,不是吗?如果
FirstNameError
是活动表单中的文本框,它永远不会为null。