我将 SpecFlow 与 Selenium WebDriver 和 SpecRun 一起用作测试运行器来创建和执行自动化测试用例,我正在寻找在测试执行报告中插入屏幕截图的解决方案。
我编写了一个方法来在每个 Assert
函数之后创建屏幕截图。图像保存到特定位置,但是当我进行结果分析时,我必须遵循报告和图像。最好将它们放在同一位置(恰好在报告 html 中)。
有什么方法可以执行此操作(类似于控制台输出)?
最佳答案
(转自https://groups.google.com/forum/#!topic/specrun/8-G0TgOBUbY)
是的,这是可能的。您必须执行以下步骤:
- 将屏幕截图保存到输出文件夹(这是运行测试的当前工作文件夹)。
- 从测试中向控制台写入一行文件:Console.WriteLine("file:///C:\fullpath-of-the-file.png");
- 确保生成的图像也作为工件保存在构建服务器上
在报告生成期间,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/