c# - NUnit 如何将屏幕截图附加到 Azure Pipeline 中的测试附件

标签 c# selenium nunit pipeline visual-studio-test-runner

我们想将屏幕截图附加到 Azure 管道中的测试附件。目前,我们使用

  • .NET 4.5.2
  • Selenium.WebDriver 3.141
  • Selenium.Chrome.WebDriver
  • Nunit 3.12.0
  • Specflow.Nunit 2.4.0

它与下面的示例类似,但我们使用 NUnit 而不是 MSTest https://learn.microsoft.com/en-us/azure/devops/pipelines/test/collect-screenshots-and-video?view=azure-devops#collect-screenshots-logs-and-attachments

在VS2017中运行程序时,可以从测试报告中获取截图。此外,我们可以在 azure 构建输出中看到屏幕截图。

代码如下:

string fileName = string.Format("Screenshot_" + DateTime.Now.ToString("dd-MM-yyyy-hhmm-ss") + ".jpg");

var artifactDirectory = Directory.GetCurrentDirectory();

ITakesScreenshot takesScreenshot = _driver as ITakesScreenshot;

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

    string screenshotFilePath = Path.Combine(artifactDirectory, fileName);

    screenshot.SaveAsFile(screenshotFilePath, ScreenshotImageFormat.Jpeg);
    TestContext.AddTestAttachment(screenshotFilePath, "screenshot");
    Console.WriteLine($"Screenshot: {new Uri(screenshotFilePath)}");
}

Azure 管道中的 Visual Studio 测试步骤

Visual Studio Test step

upload test attachments

构建运行后,没有附件

no attachments

如有任何帮助,我们将不胜感激。

最佳答案

这方面来晚了一点,但谁知道呢,这可能对遇到类似问题的人有所帮助。

我看不到您的全部代码,但发生这种情况的原因可能是,因为您正试图将附件保存在您的OneTimeSetupOneTimeTeardown 方法。引自 the documentation :

Within a OneTimeSetUp or OneTimeTearDown method, the context refers to the fixture as a whole

...这基本上意味着在 OneTimeSetupOneTimeTeardown 中不允许使用 TestContext 方法或属性(即使 NUnit/Visual Studio如果你这样做就不会提示!这会增加困惑)

因此,请确保从 TearDown 或测试用例中添加测试附件。据我所知,无法从 TestFixture 上下文中保存附件。

关于c# - NUnit 如何将屏幕截图附加到 Azure Pipeline 中的测试附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389685/

相关文章:

c# - 获取中心多边形 C#

c# - Contract.Requires 和 Contract.Ensures 的区别

c# - 将字符串转换为 datetime2

c# - 我可以只输出数据表中值的第一个实例吗?

Java、Selenium、Chrome - 无法单击按钮,即使它似乎能够很好地找到它

jquery - Selenium 测试中 $ 未定义错误

php - 无法使用带有 php 的 Selenium 将 cookie 添加到页面

testing - 在单元测试中使用依赖注入(inject)对象是个坏主意吗?

nunit - 在 ASP.NET 5 项目中运行 NUnit 测试(在 VS 测试资源管理器中)

c# - 使用 DateTimeOffset 对象的单元测试类的正确方法?