How to take screenshot for only failed test cases using selenium web driver ?

package SeleniumLearn.COM;
import org.testng.annotations.Test;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import org.apache.commons.io.FileUtils; 
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;

public class TakeScreenshot {

public WebDriver driver;                
@Test (description="take Screenshots if Test Case fails")
       public void TakeScreenshot() throws Exception {      
         driver.get("http://www.seleniumlearn.com/");
     try {                
             driver.findElement(By.id("xxxxxxxxxxxxxxxxxx")).click();
           }
    catch(Exception e) {      
             System.out.println("Element Not Found");     
             takeScreenshot();       
          }      
       }
     public void takeScreenshot() throws Exception {              
          File f = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
          FileUtils.copyFile(f, new File("/home/chinna/selenium/seleniumlearn.png")); //Linux path     
          // FileUtils.copyFile(f, new File("E:\\Workspace\\Seleniumlearn.png"));          // for windows  path
       }
@BeforeTest
     public void beforeTest() {
      driver = new FirefoxDriver();
      driver.manage().window().maximize();
  }
@AfterTest
  public void afterTest() {
  }
}

Tags: 

Comments