[英]How to fail the test if required field error message is displayed in c#?
我是測試環境的新手。 有一個基本形式,如姓名,地址等。當我單擊保存按鈕並顯示必填字段錯誤消息時,如何使測試失敗? 我可以使用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,input'First Name'”,則測試將失敗。
為此,您顯然會引入一種新的脆弱性。 如果錯誤消息更改,則測試將不再起作用。 解決該問題的方法是定義一些在UI和測試用例中使用的共享常量/消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.