Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take screenshot on test failure + exceptions

Does any of you know possible solution for taking screenshots on test failures and exceptions?

I've added following code in TearDown() but as a result it also makes screenshots on passed tests, so it is not the best solution:

DateTime time = DateTime.Now;
string dateToday = "_date_" + time.ToString("yyyy-MM-dd") + "_time_" + time.ToString("HH-mm-ss");
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile((settings.filePathForScreenShots + "Exception" + dateToday + ".png"), System.Drawing.Imaging.ImageFormat.Png);

I've already found that idea: http://yizeng.me/2014/02/08/take-a-screenshot-on-exception-with-selenium-csharp-eventfiringwebdriver/, to use WebDriverExceptionEventArgs, but for some reasons it makes also some random screenshots without any reasonable explanation.

Other ideas I found are for Java and not for NUnit which I use with Selenium, so they are pretty useless.

like image 509
Tomasz Tarnowski Avatar asked Oct 24 '15 17:10

Tomasz Tarnowski


4 Answers

If you put the screenshot logic in your TearDown method it will be called after each test finishes, no matter if it succeeded or failed.

I use a base class that has a function which wraps the tests and catches all exceptions. When a test fails the exception is caught and a screenshot is taken.

I use this base class for all my Selenium tests and it looks something like this:

public class PageTestBase
{
    protected IWebDriver Driver;

    protected void UITest(Action action)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            var screenshot = Driver.TakeScreenshot();

            var filePath = "<some appropriate file path goes here>";

            screenshot.SaveAsFile(filePath, ImageFormat.Png);

            // This would be a good place to log the exception message and
            // save together with the screenshot

            throw;
        }
    }
}

The test classes then look like this:

[TestFixture]
public class FooBarTests : PageTestBase
{
    // Make sure to initialize the driver in the constructor or SetUp method,
    // depending on your preferences

    [Test]
    public void Some_test_name_goes_here()
    {
        UITest(() =>
        {
            // Do your test steps here, including asserts etc.
            // Any exceptions will be caught by the base class
            // and screenshots will be taken
        });
    }

    [TearDown]
    public void TearDown()
    {
        // Close and dispose the driver
    }
}
like image 159
Erik Öjebo Avatar answered Oct 12 '22 08:10

Erik Öjebo


For greater justice here is the code for the MSTest

public TestContext TestContext { get; set; }

[TestCleanup]
public void TestCleanup()
{
  if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)
  {
    var screenshotPath = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss.fffff}.png";
    MyDriverInstance.TakeScreenshot().SaveAsFile(screenshotPath);
    TestContext.AddResultFile(screenshotPath);
  }
}
like image 25
Andrey Stukalin Avatar answered Oct 12 '22 08:10

Andrey Stukalin


In C# I use NUnit 3.4. This offeres the OneTimeTearDown method that is able to access the TestContext including the state of the previous executed test. Do not use TearDown because it is not executed after a test fails ;)

using OpenQA.Selenium;
using System.Drawing.Imaging;

...

[OneTimeTearDown]
public void OneTimeTearDown()
{
    if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
    {
        var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
        screenshot.SaveAsFile(@"C:\TEMP\Screenshot.jpg", ImageFormat.Jpeg);
    }
}
like image 11
Lukas Avatar answered Oct 12 '22 09:10

Lukas


YOu can achieve this easily in TestNG suite FIle Create a ScreenShot method like Below

public static void CaptureDesktop (String imgpath)
    {
        try
        {

            Robot robot = new Robot();
            Dimension screensize=Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle screenRect = new Rectangle(screensize);
            BufferedImage screenshot = robot.createScreenCapture(screenRect);
            //RenderedImage screenshot = robot.createScreenCapture(screenRect);
        ImageIO.write(screenshot, "png" , new File(imgpath));

        }

In above method i used robot class so that you can take screen shot of Dekstop also(window+WebPage) and you can call this method in different Listener class which will implements ITestListener Interface. call your screen Shot method in OntestFailure() of that Listener Class

@Override
    public void onTestFailure(ITestResult arg0) {


        String methodname = arg0.getMethod().getMethodName();
        String imgpath = "./Screenshot/"+methodname+".jpg";
        Guru99TakeScreenshot.CaptureDesktop(imgpath);

    }

This code is working for me. But this code is written in JAVA. I hope this will work in C# if not i wish this code can help you

like image 1
Rahil Kumar Avatar answered Oct 12 '22 08:10

Rahil Kumar