Tung Nguyen
Tung Nguyen

Reputation: 644

NUnit How to attach screenshot to test attachments in Azure Pipeline

We want to attach screenshots to the Test Attachment in Azure pipeline. Currently, we use

It is similar with the follwing example but we use NUnit rather than MSTest https://learn.microsoft.com/en-us/azure/devops/pipelines/test/collect-screenshots-and-video?view=azure-devops#collect-screenshots-logs-and-attachments

When run the program in VS2017, the screenshots are accessible from the test report. Also, we can see the screenshots in the azure build output.

Here is the code:

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)}");
}

Visual Studio Test step in Azure pipeline

Visual Studio Test step

upload test attachments

After the build runs, there is no attachment

no attachments

Any help would be appreciated.

Upvotes: 3

Views: 3977

Answers (1)

harveyAJ
harveyAJ

Reputation: 917

Coming in a bit late on this one, but who knows, this might be helpful to someone running into similar issues.

I cannot see your entire code, but the reason this might happen could be because you're trying to save your attachment in your OneTimeSetup or OneTimeTeardown methods. Quoting from the documentation:

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

...which basically means that using TestContext methods or properties is not allowed within OneTimeSetup or OneTimeTeardown (even though NUnit/Visual Studio won't complain if you do so! Which adds to the confusion)

So make sure you add the test's attachments from within your TearDown or test case. AFAIK, there is no way to save attachments from TestFixture context.

Upvotes: 3

Related Questions