5.4 Capture Screenshot

In order to capture screenshot, copy the below method to your common functions Class. The method create a folder named screenShots in your project root folder and saves the screenShot in .png format. The capture method can be called at any line of code by provide driver object and screenshot name as arguments.

public void capture(WebDriver driver, String ImageName) {
        File screenshot = null;
        screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        try {
            FileUtils.copyFile(screenshot, new File("screenShots/" + ImageName + ".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

We can also override the method takeScreenShotOnFailure of testNG to handle more conveniently

/**
 * Capture the screenshot on error
 * @param testResult
 * @author saikiran.nataraja
 * @throws Exception
 */
@AfterMethod 
public void takeScreenShotOnFailure(ITestResult testResult) throws Exception {
    if (testResult.getStatus() == ITestResult.FAILURE){ 
        try{
            Reporter.log(" - FAILED.",true);
            //Create Error Screenshot Directory if doesnot exists
            File dir = new File(TestReportPath+fs);
            //If SecurityManager.checkWrite(java.lang.String) method denies write access to the file.
            //Hence made the directory writable
            dir.setWritable(true); 
            dir.mkdirs();
    BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            //Here the screenshot path is reduced to a maximum of 20 literals
            File imagePath=new File(TestReportPath+fs+Dateformat+Captialize(RunOnBrowser)+".jpg");
            imagePath.setWritable(true);
            ImageIO.write(image, "JPG", imagePath);
            //Extent Reports take screenshot
            test.log(LogStatus.FAIL, "Failure Stack Trace: "+ testResult.getThrowable().getMessage());
            test.log(LogStatus.FAIL,"Snapshot below: " 
            + test.addScreenCapture(imagePath.getAbsoluteFile().toString().replace(System.getProperty("user.dir")
            +CONSTANTS.fs+"ExtentReports"+CONSTANTS.fs, "")));            
        }    
        catch (Exception e){
            Reporter.log("Class Utils | Method takeScreenshot | Exception occured while capturing ScreenShot : "
            +e.getMessage());
        }
    }else if (testResult.getStatus() == ITestResult.SKIP) {
        Reporter.log(" - SKIPPED.",true);
        test.log(LogStatus.SKIP, "Test skipped: " + testResult.getThrowable().getMessage());
        }else{
            Reporter.log(" - PASSED.",true);
            //Test is PASSED/INFO/
        }
}

Last updated

Was this helpful?