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

Lee*_*Way 2 c# selenium specflow specrun test-reporting

我使用SpecFlow硒的webdriverSpecRun为测试运行,以创建和执行自动化测试案例,我正在寻找一个解决方案,在插入测试执行报告截图.

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

有没有办法执行此操作(类似于控制台输出)?

Gas*_*agy 11

(转发自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);
        }
    }
Run Code Online (Sandbox Code Playgroud)