我有一个测试用例来验证表单。将预填充 5 个字段。如果任何一个字段为空,则提交后会出现错误消息。我正在从所有字段中获取文本并断言如果它们不为空,断言失败,因为这些字段中有一个字段为空。但是如何动态找出哪个字段为空。如果是否为空,则可能采用每个字段并断言每个字段。 但我想这将使代码变得笨拙。还有其他方法可以做到这一点吗?
以下是我的代码:
String sender = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$textsendername1")).Text;
String country = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlCountry")).Text;
String address1 = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtsenderaddress1")).Text;
String city = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtcity")).Text;
String state = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlstate")).Text;
String zip = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtzip")).Text;
try
{
Assert.IsNotEmpty(sender, country, address1, city, state, zip);
}
catch (Exception e)
{
String excep = e.ToString();
Console.WriteLine(excep);
}
我会创建一个函数来确定是否有任何字段为空,因为您可能会重复使用它。
public bool HasEmptyField()
{
string sender = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$textsendername1")).GetAttribute("value");
string country = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlCountry")).GetAttribute("value");
string address1 = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtsenderaddress1")).GetAttribute("value");
string city = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtcity")).GetAttribute("value");
string state = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlstate")).GetAttribute("value");
string zip = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtzip")).GetAttribute("value");
return string.IsNullOrEmpty(sender) ||
string.IsNullOrEmpty(country) ||
string.IsNullOrEmpty(address1) ||
string.IsNullOrEmpty(city) ||
string.IsNullOrEmpty(state) ||
string.IsNullOrEmpty(zip);
}
然后,您的脚本将如下所示
bool expectError = HasEmptyField();
driver.FindElement(submitButtonLocator).Click(); // click submit button
if (expectError)
{
Assert.True(driver.FindElements(errorMessageLocator).Any(), "Verify error message exists");
// do something to address the error message
}
// continue the script