c# - 在 SpecRun/SpecFlow 测试执行报告中插入屏幕截图

标签 c# selenium specflow test-reporting specrun

我将 SpecFlowSelenium WebDriverSpecRun 一起用作测试运行器来创建和执行自动化测试用例,我正在寻找在测试执行报告中插入屏幕截图的解决方案。

我编写了一个方法来在每个 Assert 函数之后创建屏幕截图。图像保存到特定位置,但是当我进行结果分析时,我必须遵循报告和图像。最好将它们放在同一位置(恰好在报告 html 中)。

有什么方法可以执行此操作(类似于控制台输出)?

最佳答案

(转自https://groups.google.com/forum/#!topic/specrun/8-G0TgOBUbY)

是的,这是可能的。您必须执行以下步骤:

  1. 将屏幕截图保存到输出文件夹(这是运行测试的当前工作文件夹)。
  2. 从测试中向控制台写入一行文件:Console.WriteLine("file:///C:\fullpath-of-the-file.png");
  3. 确保生成的图像也作为工件保存在构建服务器上

在报告生成期间,SpecRun 会扫描此类文件 URL 的测试输出,并将它们转换为具有相对路径的 anchor 标记,这样无论您将报告文件分发到何处(只要图像在其旁边),它们都可以使用。您当然也可以将图像放到子文件夹中。

这是与 Selenium WebDriver 一起使用的代码片段。这还会将 HTML 源代码与屏幕截图一起保存。

    [AfterScenario]
    public void AfterWebTest()
    {
        if (ScenarioContext.Current.TestError != null)
        {
            TakeScreenshot(cachedWebDriver);
        }
    }

    private void TakeScreenshot(IWebDriver driver)
    {
        try
        {
            string fileNameBase = string.Format("error_{0}_{1}_{2}",
                                                FeatureContext.Current.FeatureInfo.Title.ToIdentifier(),
                                                ScenarioContext.Current.ScenarioInfo.Title.ToIdentifier(),
                                                DateTime.Now.ToString("yyyyMMdd_HHmmss"));

            var artifactDirectory = Path.Combine(Directory.GetCurrentDirectory(), "testresults");
            if (!Directory.Exists(artifactDirectory))
                Directory.CreateDirectory(artifactDirectory);

            string pageSource = driver.PageSource;
            string sourceFilePath = Path.Combine(artifactDirectory, fileNameBase + "_source.html");
            File.WriteAllText(sourceFilePath, pageSource, Encoding.UTF8);
            Console.WriteLine("Page source: {0}", new Uri(sourceFilePath));

            ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;

            if (takesScreenshot != null)
            {
                var screenshot = takesScreenshot.GetScreenshot();

                string screenshotFilePath = Path.Combine(artifactDirectory, fileNameBase + "_screenshot.png");

                screenshot.SaveAsFile(screenshotFilePath, ImageFormat.Png);

                Console.WriteLine("Screenshot: {0}", new Uri(screenshotFilePath));
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error while taking screenshot: {0}", ex);
        }
    }

关于c# - 在 SpecRun/SpecFlow 测试执行报告中插入屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512918/

相关文章:

c# - 加密和解密文本的安全方法?

c# - 如何在 C# 中返回对字符串的引用?

java - 如何将 WebElement 存储在 json 或属性中以便我可以轻松更改它

unit-testing - 使用<unitTestProvider>的Visual Studio 2012中的Specflow错误

具有方法参数值或使用委托(delegate)的 c# 函数

c# - 在通用参数中使用多态性

angularjs - 使用 TypeScript 从页面对象返回 Promise 值

java - 无法使用 Apache POI 读取 excel 抛出 NoClassDefFoundError

.net - 如何使用 msbuild 生成 specflow feature.cs 文件?

.net - 使用 Deleporter 进行跨进程模拟