简体   繁体   中英

How to fail the test if required field error message is displayed in c#?

I am new to the testing environment. There is a basic form like name., address etc. How to fail the test when I click on save button and required field error message is displayed? I am able to locate the error message using XPath. Here's the code I tried but It is the other way around. The code I have tried passes the test when error message is displayed. Please advice how to fail the test if error message is displayed.

 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();
        }

Is there any way to fail the test if element is found? Thanks in advance.

In the case the element should not exist:

Assert.IsNull(FirstNameError);

In case the element exists, but does not contain the error message:

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

Because the XPath is so specific, these solutions are a little fragile in the sense that if your layout slightly changes, you will have to adjust your XPath expression.

To accommodate for this, you could slightly adapt your logic to say, for example:

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

Assert.IsNull(FirstNameError);

So, here we're basically saying that the test will fail if anywhere in the field set of the specified form there's a div element that contains the text "Please, enter 'First Name'."

In doing this, you would obviously introduce a new form of fragility. If your error message changes, your test will no longer work. The way to work around that would be to define some shared constants/messages that you use in both your UI and your test cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM