How to Take ScreenShot on Failure Testcases in Selenium WebDriver






Examples:

package Screenshotexp;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

public class googleScreenshot {
WebDriver driver;
@Test
public void googleScreenShot()
{
driver=new FirefoxDriver();
driver.get("https://www.google.co.in");
driver.manage().window().maximize();
//we have given wrong xpath intentionally.so test case fails
driver.findElement(By.xpath("//*[@id='gs_htif']")).sendKeys("Selenium");
}


//After Method always execute 
@AfterMethod
public void tearDown(ITestResult result)
//ITestResult.FAILURE for failed testcases
if(ITestResult.FAILURE==result.getStatus())
{
try{
 File screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
 
 //result.getname() will get testcase name and save same file for screenshot which is taken
 FileUtils.copyFile(screenshot, new File("./Screenshots/"+result.getName()+".png"));
 System.out.println("Screenshot taken");
}catch(Exception e)
{
System.out.println("Unable to  take screen shot:"+e.getMessage());
}
driver.quit();
}

}
}

Output:


Screenshot taken
FAILED: googleScreenShot

Note: After Executing this program  refresh the project .screenshots are stored with seperate folder  name  Screenshots.

No comments:

Post a Comment