你们中有人知道对测试失败和异常进行屏幕截图的可能解决方案吗?
我在中添加了以下代码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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)