【发布时间】:2016-08-12 10:47:15
【问题描述】:
我目前正在为我的公司编写基于 Web 的应用程序的测试自动化。我正在使用 C#、Visual Studio 测试套件和 Selenium 来执行测试。
今天我向我的同事提出了一个问题,即“代码中是否存在过多的 Try Catch 块?”。他的回答是不能像我现在那样工作(参见示例 1),而是让较低级别的 try-catch 抛出到较高级别的 try-catch 以便可以在那里写入异常并且测试失败(见示例 2)。
示例 1:
TestCase.cs
[TestMethod]
public void TestLogin()
{
Assert.IsTrue(FW_Shared.Perform_Login(FW_Shared.OrgCode, FW_Shared.Username, FW_Shared.Password));
Console.WriteLine(@"Login Successful");
}
FW_Shared.cs
public static class FW_Shared
{
public static string OrgCode = "Test123";
public static string Username = "Tester";
public static string Password = "Password";
public static void Perform_Login(string OrgCode, string Username, string Password)
{
try
{
Driver.Url = "http://test.app.com/";
Driver.FindElement(By.Id("org_code")).SendKeys(OrgCode);
Driver.FindElement(By.Id("username")).SendKeys(Username);
Driver.FindElement(By.Id("password")).SendKeys(Password);
Driver.FindElemenet(By.Id("btnsubmit)).Click();
}
catch (Exception ex)
{
Console.WriteLine(@"Error occurred logging on: " + ex.ToString());
return false;
}
return true;
}
}
示例 2
TestCase.cs
[TestMethod]
public void TestLogin()
{
try
{
Assert.IsTrue(FW_Shared.Perform_Login(FW_Shared.OrgCode, FW_Shared.Username, FW_Shared.Password));
Console.WriteLine(@"Login Successful");
}
catch (Exception ex)
{
Console.WriteLine(@"Exception caught, test failed: " + ex.ToString());
Assert.Fail();
}
}
FW_Shared.cs
public static class FW_Shared
{
public static string OrgCode = "Test123";
public static string Username = "Tester";
public static string Password = "Password";
public static void Perform_Login(string OrgCode, string Username, string Password)
{
try
{
Driver.Url = "http://test.app.com/";
Driver.FindElement(By.Id("org_code")).SendKeys(OrgCode);
Driver.FindElement(By.Id("username")).SendKeys(Username);
Driver.FindElement(By.Id("password")).SendKeys(Password);
Driver.FindElemenet(By.Id("btnsubmit)).Click();
}
catch (Exception)
{
throw;
}
return true;
}
}
现在我知道抛出要捕获的异常在典型编码中通常是无用的,因为您想要处理返回的特定异常,但我希望能够捕获任何一般网页或元素问题,以便测试失败关于 Web 应用程序的一般问题。例如:
- 如果网页返回 503 或 404 问题
- 如果当前网页上不存在某个元素
- 如果元素名称已更改。
在测试应用程序的其他更复杂的部分时,我使用 true/false bool 返回处理无法访问的部分/元素并断言这一点,但由于我在不同的类中引用多个函数,所以会坚持我所拥有的最好,转移到所有较低异常的顶级捕获,还是我应该做其他事情?
【问题讨论】:
-
最好的做法是不使用
try/catch。捕获异常将使追查问题的根源变得更加困难。如果您想要自定义消息,请使用适当的断言方法,如果您想确切知道哪个功能失败,请为测试方法使用显式名称:ShouldLoginSuccessfully。 -
我们对特定部分进行了验证,例如我们期望 Selenium 在哪个页面上,等等。我只是想知道一般异常捕获的最佳方法以及如何处理失败的测试.
标签: c# selenium testing automated-tests