你们中有人知道对测试失败和异常进行截图的可能解决方案吗?
我在 TearDown()
中添加了以下代码,但结果它也会对通过的测试进行截图,因此这不是最佳解决方案:
DateTime time = DateTime.Now;
string dateToday = "_date_" + time.ToString("yyyy-MM-dd") + "_time_" + time.ToString("HH-mm-ss");
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile((settings.filePathForScreenShots + "Exception" + dateToday + ".png"), System.Drawing.Imaging.ImageFormat.Png);
我已经找到了这个想法:http://yizeng.me/2014/02/08/take-a-screenshot-on-exception-with-selenium-csharp-eventfiringwebdriver/ ,使用WebDriverExceptionEventArgs
,但由于某些原因,它也做了一些随机截图,没有任何合理的解释。
我发现的其他想法是针对 Java 而不是我与 Selenium 一起使用的 NUnit,因此它们非常无用。
最佳答案
如果您将屏幕截图逻辑放在您的 TearDown 方法中,它将在每次测试完成后调用,无论它是成功还是失败。
我使用了一个基类,它有一个函数可以包装测试并捕获所有异常。当测试失败时,会捕获异常并截取屏幕截图。
我将这个基类用于我所有的 Selenium 测试,它看起来像这样:
public class PageTestBase
{
protected IWebDriver Driver;
protected void UITest(Action action)
{
try
{
action();
}
catch (Exception ex)
{
var screenshot = Driver.TakeScreenshot();
var filePath = "<some appropriate file path goes here>";
screenshot.SaveAsFile(filePath, ImageFormat.Png);
// This would be a good place to log the exception message and
// save together with the screenshot
throw;
}
}
}
测试类看起来像这样:
[TestFixture]
public class FooBarTests : PageTestBase
{
// Make sure to initialize the driver in the constructor or SetUp method,
// depending on your preferences
[Test]
public void Some_test_name_goes_here()
{
UITest(() =>
{
// Do your test steps here, including asserts etc.
// Any exceptions will be caught by the base class
// and screenshots will be taken
});
}
[TearDown]
public void TearDown()
{
// Close and dispose the driver
}
}
关于c# - 对测试失败+异常进行截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320912/