elgato
elgato

Reputation: 555

How to attach screenshot on test failure in MSTest?

I am unable to set up a proper way to attach a screenshot to TestResult if a test execution fails

The framework is set up with Visual Studio 2015, Selenium v3.141.0.

In the pass I've tried passing TestContext as an argument to a EventFiringWebDriver so I am able to attach a screenshot with EventFiringWebDriver.ExceptionThrown Event

However I am not fond passing TestContext around because the framework is divided between the Selenium assembly, containing all the page objects and the Tests assembly, containing all the testcases

TestBase.cs

[TestInitialize]
public void TestInitBase()
{
    SeleniumHelper = new HelperSelenium(TestContext);
}

HelperSelenium.cs

public HelperSelenium(TestContext testContext)
{
    Id = int.Parse(testContext.Properties["colegio"].ToString());
    WebDriver = new WebDriverSelector(testContext);
...
}

WebDriverSelector.cs

public WebDriverSelector(TestContext tc)
{
    testContext = tc;
...
    var firingWebDriver = new EventListeners(remoteDriver, testContext).GetWebDriver();
...

EventListeners.cs

public EventListeners(IWebDriver driver, TestContext testContext)
{
...

private static void UploadScreenShot()
{
    Screenshot ss = c.GetScreenshot();
    string path = Directory.GetCurrentDirectory() + "\\" +
        TestContext.TestName + "_" +
        contador + ".png";

        ss.SaveAsFile(path, ScreenshotImageFormat.Png);
        TestContext.AddResultFile(path);
}

I would want to skip passing TestContext from one class to another, however I can't think of a way to actually implement it

Upvotes: 2

Views: 1907

Answers (1)

OriBr
OriBr

Reputation: 324

The best practice is to wrap your driver with event listener and override the OnException method with your own costume screenshot taker. This way it will identify an exception anywhere and take a screenshot automatically without additional maintenance,

@Override
public void onException(Throwable throwable, WebDriver driver) {
    try
    {
        /* Take screenshot when exception happened. */
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        /* save screenshot to file. */
        FileUtils.copyFile(scrFile, new File("C:\\Workspace\\webdriverEventListenerScreenshot.png"));
    }catch(IOException ex)
    {
        ex.printStackTrace();
    }
}

Reference: https://www.dev2qa.com/webdriver-event-listener-take-screenshot-on-exception/

Edit: You can add the path to the test result / write it to trace using (Trace.WriteLine("Path"));

Upvotes: 2

Related Questions