Saturday, July 2, 2011

Can I capture a screenshot, in Selenium, when an error occurs?

I would think that you can probably just do something like this (in Perl):

     $sel->open_ok("$homepage") or
               $sel->capture_entire_page_screenshot("screenshot.jpg") 
               and BAIL_OUT("Unable to open URL");


The above will first try to open the page defined by $homepage and if it fails
will capture a screenshot AND bail out printing "Unable to open
URL"


This was an interesting question asked to me by a colleague and, as well, we have answered it in user groups a couple of times so I figured it would be worth noting here.

3 comments:

  1. It is important to note that BAIL_OUT immediately ends the test execution.

    ReplyDelete
  2. In C#, I use this code (for those who find it difficult to translate from Perl). This also creates a time-stamp as you discussed in your other blog-post. I have a settings-file where I can set the path as a var (settings.screendumppath), but you can of course just use a string instead:

    ///
    /// Create screen dump and return filename
    ///
    public static string DumpScreen()
    {
    string filename = settings.screendumppath + "seleniumdump" + DateTime.Now.ToString("ddMMyy_hhmm") + ".jpg";
    NunitTestFixture.selenium.CaptureEntirePageScreenshot(filename, "");
    return filename;
    }

    ReplyDelete
  3. Very nicely done Søren! Thanks!

    You can probably also write a separate timestamp function that you can call from anywhere, including this DumpScreen() function. So the "filename =" line would look like this:

    string filename = settings.screendumppath + "seleniumdump" + "output_of_datetime_function" + ".jpg";

    Granted you don't gain much more than having a central point to generate your timestamps as well as easier to read and manage code, but IMHO worth the effort :)

    Thoughts?

    ReplyDelete

Creative Commons License
VGP-Miami Web and Mobile Automation Blog by Alfred Vega is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.