In this post I will show you how to capture screen shot of failed test using exception handling and test marked failed in report.
In below example I handle exception using try catch block and call capture screen shot function in catch section, then throws exception make test fail.
In below example I handle exception using try catch block and call capture screen shot function in catch section, then throws exception make test fail.
package
com.webdriver.test;
import
java.io.File;
import
java.io.IOException;
import
java.util.concurrent.TimeUnit;
import
org.apache.commons.io.FileUtils;
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.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import
org.testng.annotations.Test;
public class
MyClass {
private
WebDriver driver;
private String
baseUrl;
@BeforeSuite
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.google.co.in/";
driver.manage().timeouts().implicitlyWait(30,
TimeUnit.SECONDS);
}
@Test
public void testCaptureScreenShot()
throws Exception {
try{
driver.get(baseUrl +
"/");
driver.findElement(By.cssSelector("#gb_2
> span.fffgbts")).click();
driver.findElement(By.cssSelector("#gb_1
> span.gbt")).click();
}
catch(Exception ex){
captureScreenShot("testCaptureScreenShot");
throw ex;
}
catch(Error ex){
captureScreenShot("testCaptureScreenShot");
throw ex;
}
}
public void captureScreenShot(String
name) throws IOException{
File file =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new
File(name+".jpg"));
}
@AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
}
Execute above test and you should see “testCaptureScreenShot.jpg” image will generate at root folder of your project.
No comments:
Post a Comment
Leave your comments, queries, suggestion I will try to provide solution