TestNG Selenium Capture Screenshot on failure

8,333 views
Skip to first unread message

Sella ra

unread,
Oct 18, 2010, 6:01:31 AM10/18/10
to testng...@googlegroups.com
Hi,

I am very new to Selenium.

Could you please help me with the steps to Capture Screenshot on failure using TestNG Framework in selenium?

It would be of great help to me.

Thanks lot.

Cédric Beust ♔

unread,
Oct 18, 2010, 12:17:47 PM10/18/10
to testng...@googlegroups.com
Hi Sella,

Did you read the Selenium section of the TestNG documentation?

-- 
Cédric



--
You received this message because you are subscribed to the Google Groups "testng-users" group.
To post to this group, send email to testng...@googlegroups.com.
To unsubscribe from this group, send email to testng-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/testng-users?hl=en.



--
Cédric


Sella ra

unread,
Oct 19, 2010, 3:20:10 AM10/19/10
to testng...@googlegroups.com
Hi,

I have gone through the Selenium section of TestNG documentation but did not find much help in the procedure to Capture Screenshot on failure.

Since I am new to Selenium and TestNG,could you please help me with this?

Thanks.


2010/10/18 Cédric Beust ♔ <ced...@beust.com>

Cédric Beust ♔

unread,
Oct 19, 2010, 12:19:02 PM10/19/10
to testng...@googlegroups.com, Felipe Knorr Kuhn
Felipe, do you think you could help Sella?

Would you consider adding instructions to your docs to cover screen shots as well? It's a pretty common question...

Thanks!

-- 
Cédric

Adrian Mitev

unread,
Oct 19, 2010, 1:03:17 PM10/19/10
to testng...@googlegroups.com
In general - you have to intercept the test method and take a screenshot when the test method fails. I think some abstraction and IHookable can do the trick.

2010/10/19 Cédric Beust ♔ <ced...@beust.com>



--
Although nobody can come back and make a new start, anyone can start now and make a new end

Dan

unread,
Oct 19, 2010, 1:22:40 PM10/19/10
to testng-users
In my test case tear down, I added the parameter ITestResult _result.
I check if the test failed (_result.isSuccess()) and if the failure
wasn't due to _result.getThrowable() being a selenium server error,
snap a screenshot (captureEntirePageScreenshotToString). Make sure to
not attempt screenshots in situations where selenium might have
crashed. If you'd like I can sanitize the code and post it here.

dan




On Oct 19, 10:03 am, Adrian Mitev <adrian.mi...@googlemail.com> wrote:
> In general - you have to intercept the test method and take a screenshot
> when the test method fails. I think some abstraction and IHookable can do
> the trick.
>
> 2010/10/19 Cédric Beust ♔ <ced...@beust.com>
>
>
>
>
>
> > Felipe, do you think you could help Sella?
>
> > Would you consider adding instructions to your docs to cover screen shots
> > as well? It's a pretty common question...
>
> > Thanks!
>
> > --
> > Cédric
>
> > On Tue, Oct 19, 2010 at 12:20 AM, Sella ra <sellara...@gmail.com> wrote:
>
> >> Hi,
>
> >> I have gone through the Selenium section of TestNG documentation but did
> >> not find much help in the procedure to Capture Screenshot on failure.
>
> >> Since I am new to Selenium and TestNG,could you please help me with this?
>
> >> Thanks.
>
> >> 2010/10/18 Cédric Beust ♔ <ced...@beust.com>
>
> >> Hi Sella,
>
> >>> Did you read the Selenium section of the TestNG documentation?
>
> >>> --
> >>> Cédric
>
> >>> On Mon, Oct 18, 2010 at 3:01 AM, Sella ra <sellara...@gmail.com> wrote:
>
> >>>> Hi,
>
> >>>> I am very new to Selenium.
>
> >>>> Could you please help me with the steps to Capture Screenshot on failure
> >>>> using TestNG Framework in selenium?
>
> >>>> It would be of great help to me.
>
> >>>> Thanks lot.
>
> >>>>  --
> >>>> You received this message because you are subscribed to the Google
> >>>> Groups "testng-users" group.
> >>>> To post to this group, send email to testng...@googlegroups.com.
> >>>> To unsubscribe from this group, send email to
> >>>> testng-users...@googlegroups.com<testng-users%2Bunsubscribe@google groups.com>
> >>>> .
> >>>> For more options, visit this group at
> >>>>http://groups.google.com/group/testng-users?hl=en.
>
> >>> --
> >>> Cédric
>
> >>>  --
> >>> You received this message because you are subscribed to the Google Groups
> >>> "testng-users" group.
> >>> To post to this group, send email to testng...@googlegroups.com.
> >>> To unsubscribe from this group, send email to
> >>> testng-users...@googlegroups.com<testng-users%2Bunsubscribe@google groups.com>
> >>> .
> >>> For more options, visit this group at
> >>>http://groups.google.com/group/testng-users?hl=en.
>
> >>  --
> >> You received this message because you are subscribed to the Google Groups
> >> "testng-users" group.
> >> To post to this group, send email to testng...@googlegroups.com.
> >> To unsubscribe from this group, send email to
> >> testng-users...@googlegroups.com<testng-users%2Bunsubscribe@google groups.com>
> >> .
> >> For more options, visit this group at
> >>http://groups.google.com/group/testng-users?hl=en.
>
> > --
> > Cédric
>
> >  --
> > You received this message because you are subscribed to the Google Groups
> > "testng-users" group.
> > To post to this group, send email to testng...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > testng-users...@googlegroups.com<testng-users%2Bunsubscribe@google groups.com>
> > .

Sella ra

unread,
Oct 20, 2010, 9:01:56 PM10/20/10
to testng...@googlegroups.com
 
Hi,
 
Thanks lot for your reply.
 
It would be of great help if you could provide me the code.
 
 
Thanks.

To unsubscribe from this group, send email to testng-users...@googlegroups.com.

ajay mehra

unread,
Oct 21, 2010, 12:37:30 AM10/21/10
to testng...@googlegroups.com
I think this might help,
 
 
package test.Lib;
 
import java.io.File;
 
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
 
public class Screenshot extends TestListenerAdapter {
     @Override
   public void onTestFailure(ITestResult result) {
    File file = new File("");
    
   Reporter.setCurrentTestResult(result);
    System.out.println(file.getAbsolutePath());
    Reporter.log(file.getAbsolutePath());
   
    Reporter.log("screenshot saved at "+file.getAbsolutePath()+"\\reports\\"+result.getName()+".jpg");
    Reporter.log("<a href='../"+result.getName()+".jpg' <img src='../"+result.getName()+".jpg' hight='100' width='100'/> </a>");
    BaseClass.selenium.captureScreenshot(file.getAbsolutePath()+"\\reports\\"+result.getName()+".jpg");
    Reporter.setCurrentTestResult(null);
   }
   
   @Override
  public void onTestSkipped(ITestResult result) {
  // will be called after test will be skipped
   }
  
   @Override
   public void onTestSuccess(ITestResult result) {
  // will be called after test will pass
   }
   
}

Dan

unread,
Oct 21, 2010, 2:30:06 PM10/21/10
to testng-users
Try something like this. Please double check it as I quickly ripped it
from my existing code and tried to make it read a bit clearer:

@AfterMethod(alwaysRun=true)
public void postTestCase(ITestResult _result) {
// Do some logging right here
if (!(_result.getThrowable() != null &&
_result.getThrowable().getMessage().equals("Internal Server Error")))
{
// If there is a throwable, it can't be due to a selenium crash
because then we can't take a screenshot
if (!_result.isSuccess()) {
// Different screenshot options include this:
String base64Screenshot =
selenium.captureEntirePageScreenshotToString("");
byte[] decodedScreenshot =
Base64.decodeBase64(base64Screenshot.getBytes());
File file = new File(SOMELOCATION);
FileOutputStream fos = new FileOutputStream(file);
fos.write(decodedScreenshot);
fos.close();

// or this: captureEntirePageScreenshot();
// or these: captureScreenshot()/captureScreenshotToFile()
}
selenium.stop();
}
// Do some logging right here
}


On Oct 20, 6:01 pm, Sella ra <sellara...@gmail.com> wrote:
> Hi,
>
> Thanks lot for your reply.
>
> It would be of great help if you could provide me the code.
>
> > <testng-users%2Bunsubscribe@google groups.com>
> >  > > .
> > > > For more options, visit this group at
> > > >http://groups.google.com/group/testng-users?hl=en.
>
> > > --
> > > Although nobody can come back and make a new start, anyone can start now
> > and
> > > make a new end
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "testng-users" group.
> > To post to this group, send email to testng...@googlegroups.com.
> > To unsubscribe from this group, send email to

Felipe Knorr Kuhn

unread,
Oct 21, 2010, 2:34:52 PM10/21/10
to testng...@googlegroups.com
You can use that on a TestListener:
http://testng.org/javadocs/org/testng/ITestListener.html

I don't have any code here as I'm thousands of miles away from home, sorry.

> To unsubscribe from this group, send email to testng-users...@googlegroups.com.

Sella ra

unread,
Oct 21, 2010, 11:50:20 PM10/21/10
to testng...@googlegroups.com

Thanks for the solutions.
Will try out these solutions.


Thanks.

Kartik Kumar

unread,
Oct 22, 2010, 1:06:50 AM10/22/10
to testng...@googlegroups.com
You can set up listener in your configuration method as follows.

@BeforeMethod
public void setUp(ITestContext context) {
   TestRunner runner = (TestRunner) context;
   runner.addListener(new ScreenshotListener());
}

You can follow any of the methods to capture screen shot.

Cédric Beust ♔

unread,
Oct 22, 2010, 10:36:57 AM10/22/10
to testng...@googlegroups.com
On Thu, Oct 21, 2010 at 10:06 PM, Kartik Kumar <krishn...@gmail.com> wrote:
You can set up listener in your configuration method as follows.

@BeforeMethod
public void setUp(ITestContext context) {
   TestRunner runner = (TestRunner) context;
   runner.addListener(new ScreenshotListener());
}

Note that this is not officially supported (TestRunner is an internal class).

Setting up your listener before your tests start is the recommended way to do this.

--
Cédric


Kartik Kumar

unread,
Oct 23, 2010, 6:03:02 AM10/23/10
to testng...@googlegroups.com
I actually saw this implementation. It seems to be supported by Selenium itself.

2010/10/22 Cédric Beust ♔ <ced...@beust.com>
Cédric


--
You received this message because you are subscribed to the Google Groups "testng-users" group.
To post to this group, send email to testng...@googlegroups.com.

Kartik Kumar

unread,
Oct 23, 2010, 6:03:19 AM10/23/10
to testng...@googlegroups.com

Cédric Beust ♔

unread,
Oct 23, 2010, 9:07:17 AM10/23/10
to testng...@googlegroups.com
On Sat, Oct 23, 2010 at 3:03 AM, Kartik Kumar <krishn...@gmail.com> wrote:
I actually saw this implementation. It seems to be supported by Selenium itself.

It will stop working if I decide one day that I no longer want TestRunner to implement ITestContext...

--
Cédric


Adam Goucher

unread,
Oct 26, 2010, 2:56:02 PM10/26/10
to testng...@googlegroups.com
Does anyone care to prepare the summarized version of a solution to this
given this warning (including registration of it outside of testng.xml)?
Preferably hybridizing Ajay's extension of TestListenerAdapter with
Dan's filtration of internal Se errors.

Figured I would ask before having to do it myself. :)

-adam

> It will stop working if I decide one day that I no longer want
> TestRunner to implement ITestContext...
>
> --

> C�dric

Felipe Knorr Kuhn

unread,
Oct 26, 2010, 6:28:13 PM10/26/10
to testng...@googlegroups.com
Adam,

I have it at home, so if you can't wait one week while I'm still
enjoying the States, you are free to go ahead and implement it
yourself :)

FK

Adam Goucher

unread,
Oct 26, 2010, 6:42:00 PM10/26/10
to testng...@googlegroups.com
I can wait. Not as if I don't already have enough things to do already. :)

-adam


> Adam,
>
> I have it at home, so if you can't wait one week while I'm still
> enjoying the States, you are free to go ahead and implement it
> yourself :)
>
> FK
>
> On Tue, Oct 26, 2010 at 4:56 PM, Adam Goucher<ad...@goucher.ca> wrote:
>> Does anyone care to prepare the summarized version of a solution to this
>> given this warning (including registration of it outside of testng.xml)?
>> Preferably hybridizing Ajay's extension of TestListenerAdapter with Dan's
>> filtration of internal Se errors.
>>
>> Figured I would ask before having to do it myself. :)
>>
>> -adam
>>
>>> It will stop working if I decide one day that I no longer want TestRunner
>>> to implement ITestContext...
>>>
>>> --

>>> C�dric

zihao

unread,
Nov 2, 2010, 7:01:44 PM11/2/10
to testng-users
How to embed the captured images into final report or are they embeded
automatically by TestNG?

On Oct 26, 6:42 pm, Adam Goucher <a...@goucher.ca> wrote:
> I can wait. Not as if I don't already have enough things to do already. :)
>
> -adam
>
>
>
>
>
>
>
> > Adam,
>
> > I have it at home, so if you can't wait one week while I'm still
> > enjoying the States, you are free to go ahead and implement it
> > yourself :)
>
> > FK
>

Dan

unread,
Nov 3, 2010, 1:44:59 PM11/3/10
to testng-users
Good question. I was just logging a hyperlink but it would be cool to
embed it directly in. Cedric, is there a way to do this?

Cédric Beust ♔

unread,
Nov 3, 2010, 2:02:19 PM11/3/10
to testng...@googlegroups.com, Felipe Knorr Kuhn
On Wed, Nov 3, 2010 at 10:44 AM, Dan <dan.h...@gmail.com> wrote:
Good question. I was just logging a hyperlink but it would be cool to
embed it directly in. Cedric, is there a way to do this?

You would probably need to write your own Reporter since TestNG has no idea what kind of files the reporters create, so it can't generate HTML that depends on that information...

That being said, considering the big mind share that the association TestNG+Selenium has, I would be open to adding specific code that would make TestNG more aware that it's running Selenium tests, and in such cases, generate reports that contain more Selenium specific information, such as embedded screen shots.

What do the Selenium experts think? How would such an interface between TestNG and Selenium look like? (Felipe, any thoughts?)

-- 
Cédric

Felipe Knorr Kuhn

unread,
Nov 3, 2010, 2:22:26 PM11/3/10
to Cédric Beust ♔, testng...@googlegroups.com
Cédric,

Perhaps an annotation option would suffice @Test(type=selenium) (just an idea, I don't like to say "I'm running some selenium tests" myself)

I don't know what to do from there, though, as there are infinite possibilities to write your tests.

For dealing with screenshots, for example:

Elias Nogueira has written a lib to generate PDF reports including screenshots using Jasper, I think: http://code.google.com/p/selenium-java-evidence/wiki/HowToUse?wl=en - but should be only for JUnit

I took the aspect oriented approach and used AspectJ and some pointcuts to take screenshots and generate a PDF report for every test case using Flying Saucer+IText automagically.

Like I said, it all depends on how you write your tests.

What could be helpful is a way to get the full output directory (getDirectoryOutput + separator + getTestName + screenshotFilePath) easier, and make the TestNG reporter iterate over the screenshots in the output dir, adding <img src="file"> to the HTML report.

Then again, one could do it extending ReportNG (which has much better HTML reporting) as well, so...

FK

2010/11/3 Cédric Beust ♔ <ced...@beust.com>

AnthonyK

unread,
Jan 24, 2012, 11:13:44 AM1/24/12
to testng...@googlegroups.com
I came across this while try to figure out how to do this myself.....i have a solution which works great for me. I use Selenium WebDriver, TestNG and non-remote webdriver instances.....


here's my implementation, i have a WebDriverManager static class which i use to hold the driver reference and i have getter methods for the instance and browser being used etc, a bit dirty maybe for the purists?!.....hope it helps....


import com.opera.core.systems.OperaDesktopDriver;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * Author: 
 * Date: 13/01/2012
 *
 * Summary: 
 * Implementation of a listener to take screen shots when using web driver for tests that fail. Screen shots
 * are saved to a screen shots folder on the users Desktop in the folder /Desktop/Test-Failure-Screenshots/, must
 * have admin rights so the folder is created and saved etc.
 *
 * Dependencies:
 * Requires an instance of the browsers web driver as this class calls the WebDriverManager to get the 
 * browsers web driver instance.
 *
 */

public class CaptureScreenshotOnFailureListener extends TestListenerAdapter
{
    @Override
    public void onTestFailure (ITestResult testResult)
    {
        // call the superclass
        super.onTestFailure(testResult);

        // Get a driver instance from the web driver manager object
        WebDriver driver =  WebDriverManager.getDriverInstance();

        /*
         * We can only take screen shots for those browsers that support screen shot capture, html unit
         * does not support screenshots as part of its capabilities.
         */
        if ( (driver instanceof InternetExplorerDriver) || (driver instanceof FirefoxDriver)
                                                                       || (driver instanceof ChromeDriver)
                                                                       || (driver instanceof OperaDesktopDriver))
        {
            // Create a calendar object so we can create a date and time for the screenshot
            Calendar calendar = Calendar.getInstance();

            // Get the users home path and append the screen shots folder destination
            String userHome = System.getProperty("user.home");
            String screenShotsFolder = userHome + "\\Desktop\\Test-Failure-Screenshots\\";

            // The file includes the the test method and the test class
            String testMethodAndTestClass = testResult.getMethod().getMethodName() + "(" + testResult.getTestClass().getName() + ")";

            System.out.println(" *** This is where the capture file is created for the Test \n" + testMethodAndTestClass );

            // Create the filename for the screen shots
            String filename = screenShotsFolder + WebDriverManager.getBroswer() + "-"
                                                + testMethodAndTestClass + "-"
                                                + calendar.get(Calendar.YEAR) + "-"
                                                + calendar.get(Calendar.MONTH) + "-"
                                                + calendar.get(Calendar.DAY_OF_MONTH) + "-"
                                                + calendar.get(Calendar.HOUR_OF_DAY) + "-"
                                                + calendar.get(Calendar.MINUTE) + "-"
                                                + calendar.get(Calendar.SECOND) + "-"
                                                + calendar.get(Calendar.MILLISECOND)
                                                + ".png";

            // Take the screen shot and then copy the file to the screen shot folder
            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

            try  {
                FileUtils.copyFile(scrFile, new File(filename));
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

        } // end of if

    } // end of onTestFailure

} // enf of class


to get this to actually work you need to register the listener with a line before each test class method as follows..........



import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.ITestContext;


/*
 * Listener implementation to capture screenshots on filure for TestNG
 */
@Listeners(CaptureScreenshotOnFailureListener.class)

public class MyTestClass
{

    @BeforeClass
    public static void setUp(ITestContext context) throws Exception
    {
        // get the web driver parameters from the testng xml file
        String browser = context.getCurrentXmlTest().getParameter("browser");
        String url         = context.getCurrentXmlTest().getParameter("url");

        driver = WebDriverManager.startDriver(browser, url, 40);
    }

    @Test()
    public void xyz() throws Exception
    {
        ........
    }
}

this then gives me screenshots in a designated folder like the following....

CHROME-validateAdministratorPortalPageTitle(AdministratorSignInPageTests)-2012-0-20-16-59-56-744


any comments etc ?


Hope this helps people and i had to gather this from a number of posts and figured it out from Cedric's TestNG book and the TestNG API....easier than JUnit rules!!!!

sabf

unread,
Feb 1, 2012, 2:12:01 AM2/1/12
to testng...@googlegroups.com
Hello AnthonyK,

please can you give an example how does your WebDriverManager static class looks like?

Thanks,
sabf

AnthonyK

unread,
Feb 2, 2012, 8:53:16 AM2/2/12
to testng...@googlegroups.com
essentially looks like the following...
 
 
/**
 * Author: anthony.kearns

 * Date: 13/01/2012
 *
 * Summary:
 * Implementation of a web driver manager static class that is used to start and stop web driver for different
 * browser implementations.
 *
 * Dependencies:
 * To use the Chrome browser driver the user must download and setup the chrome browser driver locally.
 *
 */

public class WebDriverManager
{
    private static WebDriver driver = null;
    private static String browser = null;

     // Default constructor, no need to extend this just use as a static
    public WebDriverManager()   {
    }

    /**
     * Static method for starting a webdriver, defaults  the wait time to 30 seconds and the browser to
     * the firefox driver.
     */
    public static WebDriver startDriver(String browser, String portalUrl, int timeout)
    {
        WebDriverManager.browser = browser;

        /*
        * Determine what browser were using and start the appropiate driver instance
        */
        if ( browser.equalsIgnoreCase("INTERNET_EXPLORER") )
        {
            System.out.println("browser : "+ browser);

            // start a internet explorer driver instance
            driver = new InternetExplorerDriver();

            driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);

            // open the url
            driver.get(portalUrl);

            driver.manage().deleteAllCookies();

            new Actions(driver).keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();
 
            // click the override link if it exists
            try
            {
                driver.navigate().to("javascript:document.getElementById('overridelink').click()");
            }
            catch (Exception e) {
                // do nothing as this exception is expected if no security ssl cert issue
            }

        }
        else if ( browser.equalsIgnoreCase("HTML_UNIT") )
        {
            System.out.println("browser : "+ browser);

            // start a html unit driver instance and enable javascript
            driver = new HtmlUnitDriver(true);

            driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);

            // open the url
            driver.get(portalUrl);

            driver.manage().deleteAllCookies();

            new Actions(driver).keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();

        }
        /**
         *  Installation and configuration steps for the Chrome driver.....
         *
         *  1. Go to http://code.google.com/p/chromium/downloads/list and download the latest chromedriver for windows
         *  2. Extract the chromedriver.exe to a location of your choice
         *  3. Create a webdriver.chrome.driver environment variable and set the path to the chromedriver.exe including
         *     the chromedriver.exe in the path.
         */
        else if ( browser.equalsIgnoreCase("CHROME") )
        {
            System.out.println("browser :"+ browser);

            /**
             * Chrome web driver requires a webdriver.chrome.driver property to be set to the path of the
             * chrome driver exe so create a webdriver.chrome.driver environment variable and determine
             * where the driver exe resides for each machine instance via this variable.
             * Use the environment variable to then set the property.
             */
            try
            {
                String chromeDriverPath = System.getenv( "webdriver.chrome.driver" );
                System.setProperty("webdriver.chrome.driver", chromeDriverPath);
            }
            catch (Exception ex)
            {
                System.out.println("\nException in getting and setting the webdriver chrome driver: "
                                                    + ex.getMessage() + ex.getClass() );
                ex.printStackTrace();
            }
            /*
             * Configure chrome to ignore the untrusted certificate error for secure ssl. More information can
             * be found here...
             *
             * http://code.google.com/p/selenium/wiki/ChromeDriver
             */
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList(new String[]{"--ignore-certificate-errors", "--start-maximized"}));

            driver = new ChromeDriver(options);

            driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);

            // open the url
            driver.get(portalUrl);

            driver.manage().deleteAllCookies();

            new Actions(driver).keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();
        }
        else if ( browser.equalsIgnoreCase("OPERA") )
        {
            System.out.println("browser :"+ browser);

            DesiredCapabilities operaCapabilities = DesiredCapabilities.opera();
            operaCapabilities.setJavascriptEnabled(true);
            operaCapabilities.setCapability("-autotestmode", true);

            driver = new OperaDriver(operaCapabilities);

            driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);

            // open the url
            driver.get(portalUrl);

            driver.manage().deleteAllCookies();

            new Actions(driver).keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();

        }
        else
        {
            System.out.println("browser : Firefox (Default)\n");

            // start a firefox driver instance
            driver = new FirefoxDriver();

            driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);

            // open the url
            driver.get(portalUrl);

            driver.manage().deleteAllCookies();

            new Actions(driver).keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();

        }

        // return a reference to the static web driver instance started
        return driver;
    }


    /**
     * Stops the browser driver started
     *
     * @param - the instance of the driver to stop
     */
 public static void stopDriver()
    {
        driver.quit();
    }

    public static WebDriver getDriverInstance()
    {
        return driver;
    }

    /**
     * Getter method for the currect browser being used for testing
     * @return the browser string being used for testing
     */
    public static String getBroswer()
    {
        return browser;
    }


   
   

} //end class

Mathy

unread,
Feb 3, 2012, 8:52:40 AM2/3/12
to testng...@googlegroups.com

Hi,

can anyone help me in using the screenshot in build Ant file.. i got the
below code from Google search but when implemented i am getting some
errors... build failed.. can you give me the ant file with the listeners
below.. thanks

<testng listeners="org.fest.swing.testng.ScreenshotOnFailureListener"
outputDir="${target.test.results.dir}" haltOnFailure="true"
verbose="2">
<classfileset dir="${target.test.classes.dir}" includes="**/*Test.class"
/>
<classpath location="${target.test.classes.dir}" />
<classpath location="${target.classes.dir}" />
<classpath refid="test.classpath" />
</testng>

Sella ra wrote:
>
> Hi,
>
> I am very new to Selenium.
>
> Could you please help me with the steps to Capture Screenshot on failure
> using TestNG Framework in selenium?
>
> It would be of great help to me.
>
> Thanks lot.
>

> --
> You received this message because you are subscribed to the Google Groups
> "testng-users" group.
> To post to this group, send email to testng...@googlegroups.com.
> To unsubscribe from this group, send email to
> testng-users...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/testng-users?hl=en.
>
>
>

--
View this message in context: http://old.nabble.com/TestNG-Selenium-Capture-Screenshot-on-failure-tp29991790p33256726.html
Sent from the testng-users mailing list archive at Nabble.com.

Mathy

unread,
Feb 3, 2012, 8:55:14 AM2/3/12
to testng...@googlegroups.com

Hi,

can anyone help me in using the screenshot code in build Ant file and
testng.xml.. i got the below code from Google search but when implemented i


am getting some errors... build failed.. can you give me the ant file with
the listeners below.. thanks

<testng listeners="org.fest.swing.testng.ScreenshotOnFailureListener"
outputDir="${target.test.results.dir}" haltOnFailure="true"
verbose="2">
<classfileset dir="${target.test.classes.dir}" includes="**/*Test.class"
/>
<classpath location="${target.test.classes.dir}" />
<classpath location="${target.classes.dir}" />
<classpath refid="test.classpath" />
</testng>

--
View this message in context: http://old.nabble.com/TestNG-Selenium-Capture-Screenshot-on-failure-tp29991790p33256729.html

Mathy

unread,
Feb 3, 2012, 8:55:46 AM2/3/12
to testng...@googlegroups.com

Hi,

can anyone help me in using the screenshot in build Ant file and
TestNg.xml.. i got the below code from Google search but when implemented i


am getting some errors... build failed.. can you give me the ant file with
the listeners below.. thanks

<testng listeners="org.fest.swing.testng.ScreenshotOnFailureListener"
outputDir="${target.test.results.dir}" haltOnFailure="true"
verbose="2">
<classfileset dir="${target.test.classes.dir}" includes="**/*Test.class"
/>
<classpath location="${target.test.classes.dir}" />
<classpath location="${target.classes.dir}" />
<classpath refid="test.classpath" />
</testng>
--

View this message in context: http://old.nabble.com/TestNG-Selenium-Capture-Screenshot-on-failure-tp29991790p33256730.html

Ranjith kumar

unread,
Feb 2, 2013, 6:21:02 AM2/2/13
to testng...@googlegroups.com
Hi Anthony,

Nice Post.... thanks for sharing...... keep up your good work...

Thanks....
By
K.Ranjithkumar

lost.ou...@gmail.com

unread,
Aug 27, 2013, 5:06:22 AM8/27/13
to testng...@googlegroups.com
Thakns for the post but i cant not understand "WebDriver driver =  WebDrive.getDriverInstance(); In my listener class  (MyTestListener) the WebDriver driver =  WebDrive.getDriverInstance() line shows an error. but i can not understand. please reply as early as possible... Here is my listener class code ... and my test code

listener class code

public class MyTestListener extends TestListenerAdapter {
Selenium selenium;
//WebDriver driver = new FirefoxDriver();

//WebDriverHandler driver = new FirefoxDriver();
 
  public void onFinish(ITestContext result) {
 
// System.out.println("FINISHED.....................");
 
  }
  public void onStart(ITestContext result) {
 
//  System.out.println("START.....................");
  }

  @Override
  public void onTestFailure(ITestResult result) {
 
 // call the superclass 
         super.onTestFailure(result); 
 
 
         // Get a driver instance from the web driver manager object 
         WebDriver driver =  WebDrive.getDriverInstance(); 
 
 
         /* 
          * We can only take screen shots for those browsers that support screen shot capture, html unit 
          * does not support screenshots as part of its capabilities. 
          */ 
         if ( (driver instanceof InternetExplorerDriver) || (driver instanceof FirefoxDriver) 
                                                                        || (driver instanceof ChromeDriver) 
                                                                        || (driver instanceof OperaDesktopDriver)) 
         { 
             // Create a calendar object so we can create a date and time for the screenshot 
             Calendar calendar = Calendar.getInstance(); 
 
 
             // Get the users home path and append the screen shots folder destination 
             String userHome = System.getProperty("user.home"); 
             String screenShotsFolder = userHome + "\\Desktop\\Test-Failure-Screenshots\\"; 
 
 
             // The file includes the the test method and the test class 
             String testMethodAndTestClass = result.getMethod().getMethodName() + "(" + result.getTestClass().getName() + ")"; 
 
 
             System.out.println(" *** This is where the capture file is created for the Test \n" + testMethodAndTestClass ); 
 
 
             // Create the filename for the screen shots 
             String filename = screenShotsFolder + WebDriverManager.getBroswer() + "-" 
                                                 + testMethodAndTestClass + "-" 
                                                 + calendar.get(Calendar.YEAR) + "-" 
                                                 + calendar.get(Calendar.MONTH) + "-" 
                                                 + calendar.get(Calendar.DAY_OF_MONTH) + "-" 
                                                 + calendar.get(Calendar.HOUR_OF_DAY) + "-" 
                                                 + calendar.get(Calendar.MINUTE) + "-" 
                                                 + calendar.get(Calendar.SECOND) + "-" 
                                                 + calendar.get(Calendar.MILLISECOND) 
                                                 + ".png"; 
 
 
             // Take the screen shot and then copy the file to the screen shot folder 
             File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
 
 
             try  { 
                 FileUtils.copyFile(scrFile, new File(filename)); 
             } 
             catch (IOException e) 
             { 
                 e.printStackTrace(); 
             } 
 
 
         } // end of if 
}

  @Override
  public void onTestSkipped(ITestResult result) {
  System.out.println("Skipped test: "+result.getName()+"Reason:"+result.getThrowable());
  }

  @Override
  public void onTestStart(ITestResult result) {
  System.out.println("Starting Test: "+result.getName());
  }
  @Override
  public void onTestSuccess(ITestResult result) {
  System.out.println("Finished Executing Test: "+result.getName()+"Status: Success.");
}
 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
  System.out.println("Test failed but within success percentage");

  }
}

Test Code


@Listeners(com.selenium.datamoat.MyTestListener.class)
//@Listeners(com.selenium.datamoat.SuiteReporter.class)
public class testFAQTab {


WebDriver driver;
Selenium selenium;

@BeforeMethod
public void startSelenium(ITestContext context) throws Exception{
driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, "http://www.asdfg.com/");
    
}
 @AfterMethod(alwaysRun=true) 
public void StopSelenium(ITestResult result) throws Exception {
        driver.quit();


@Test(priority = 0)
public void testAllTextofFAQTab (){


System.out.println ("\n1. Verify correct text is present in the correct location of 'FAQ' tab. \n");
selenium.open("https://www.asdfg.com/");
selenium.click("link=FAQ");
assertEquals(selenium.getTitle(),"Datamoat | FAQ");

//Verifying The Text using xpath
String text1=driver.findElement(ByXPath.xpath("//table/tbody/tr[4]/td/table/tbody/tr[2]/td/p")).getText();
System.out.println(text1);
assertEquals(text1, "Question 1. What is Online Data Backup service?");

Madhan Gopal Reddy

unread,
Sep 6, 2013, 11:15:35 AM9/6/13
to testng...@googlegroups.com
Thanks... great explanation...

shuklasa...@gmail.com

unread,
Sep 12, 2013, 2:36:27 AM9/12/13
to testng...@googlegroups.com
try to write your own listener and implement onTestFailure method of TestListenerAdapter class
inside that you can put screenshot code 
               File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
   FileUtils.copyFile(scrFile, new File(path to that screenshot image));
Reply all
Reply to author
Forward
0 new messages