I am new at Selenium and came up with an issue - how to take and save screenshot into the specific folder. I am using Selenium C# NUnit bond.
Have read many information on this but most of them is on - how to capture screenshot and add it to html file. But this is not what I need.
I need the screenshot file to be save into a folder so when I'm running Pipeline in AzureDevOps the "Tests results" block contain this screenshot as well and display it.
I was using this part of the code. The test runs and fails, but no screenshot was make
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (TestContext.CurrentContext.Result.Outcome != ResultState.Failure)
{
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var filePath = "pathToTheFolder\\Screenshots\\";
screenshot.SaveAsFile(filePath, Png);
}
}
Maybe someone can help on this and maybe share the knowledge and the code as well)
Thank you all!
CodePudding user response:
Try
using System.Drawing; //add this using statement
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (TestContext.CurrentContext.Result.Outcome != ResultState.Failure)
{
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var filePath = "pathToTheFolder\\Screenshots\\";
screenshot.SaveAsFile(filePath System.Drawing.Imaging.ImageFormat.Png);
}
}
This tutorial looks like what you need
CodePudding user response:
Found a way how to reach out my goal - to save screenshots for failed tests in a bin folder of the project and attach them to the Pipeline "Test Result" section in further. This is the final workable code. I have removed it from [OneTimeTearDown] and set it to [TearDown]. And also have added attachment with the last row, that allows to sent screenshots to Pipelines "Test result" block.
This is my Base.cs file where I am locating IWebDriver, all Setup and TearDown methods
using E2E_Tests.TestData;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using WebDriverManager.DriverConfigs.Impl;
using OpenQA.Selenium.Chrome;
using System.Configuration;
using NUnit.Framework.Interfaces;
[TearDown]
public void TearDown()
{
TakeScreenshotDefaultImageFormat();
driver.Close();
}
public void TakeScreenshotDefaultImageFormat()
{
if (TestContext.CurrentContext.Result.Outcome == ResultState.Error)
{
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var screenshotDirectoryPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Screenshots\\");
if (!Directory.Exists(screenshotDirectoryPath))
{
Directory.CreateDirectory(screenshotDirectoryPath);
}
var currentDate = DateTime.Now;
var filePath = $"{screenshotDirectoryPath}{TestContext.CurrentContext.Test.Name}_{currentDate.ToString("yyyy.MM.dd-HH.mm.ss")}.png";
screenshot.SaveAsFile(filePath);
TestContext.AddTestAttachment(filePath);
}
}