c# - 对测试失败+异常进行截图

标签 c# .net unit-testing selenium nunit

你们中有人知道对测试失败和异常进行截图的可能解决方案吗?

我在 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/

相关文章:

c# - Sitecore 子布局中的字符串中缺少正斜杠

c# - 重新格式化文件的代码

java - 可以在 TestNG 测试服中使用继承吗?

c# - 如何模拟静态单例?

c# - 为什么 BCL Collections 使用结构体枚举器,而不是类?

c# - 系统无法读取我的图片上传文件(?)

c# - 如何让 silverlight 从 MySQL 获取数据

java - Java 中的 HMAC-SHA256/从 C# 翻译

c++ - (make/g++) 包括自动生成的依赖目标的完整路径? (或解决方法)

c# - 如何将两个 .cs 文件编译成单个 DLL?