Take screen shots using selenium webdriver



  • How to take screen shot on both test cases "Positive and Negative" results?

    NOTE: Currently, I am working in selenium webdriver (junit) and I did not have an idea about how to code for adding methods to take screen shots.



  • Take the screenshot in the @After test tear down method, which is run after every test. This way you will always get a screenshot for both passed and failed tests.

    public class TestSample
    {
        static WebDriver driver;
    
    @Before
    public void setUp() {
        //start new webdriver session, for eg using firefox
        driver = new FirefoxDriver();
    } 
    
    @Test
    public void aTest() {
        driver.get("http://www.google.com/");
        //more test logic  - test might pass or fail at this point
    }
    
    @After
    public void tearDown() {
        // take the screenshot at the end of every test
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        // now save the screenshto to a file some place
        FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
    
    //quit WebDriver session
        driver.quit();
    }
    

    }



Suggested Topics