小编典典

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

selenium

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

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

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


阅读 334

收藏
2020-06-26

共1个答案

小编典典

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

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

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

在生成报告的过程中,SpecRun会在测试输出中扫描此类文件URL,并将其转换为具有相对路径的锚标记,以便它们在分发报告文件的任何地方都可以使用(只要图像在该文件旁边)。当然,您也可以将图像捆绑到子文件夹中。

这是与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);
        }
    }
2020-06-26