How to take Screenshots if Test Case fails?


One basic question which comes in everyone's mind is : What happens if test case fails? Where was the error in script and How can we capture it?

So, the solutions is always (at least in most of the cases) to take screenshots of webpage when the test run fails.

With one look at the screenshot we can get an idea of where exactly the script got failed. Moreover reading screenshot is easier compare to reading 100's of console errors

To get screenshot on test failure, we should put the entire code in try-catch block. In the catch block we should paste the screenshot code:

public class TakeScreenshot {
 
   WebDriver driver;
 
 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }


 @Test
 public void Test() throws IOException{
 try{
  driver.get("https://mail.google.com/");
  driver.findElement(By.id("link-signup")).click();
  driver.findElement(By.name("FirstName")).sendKeys("First Name");
  driver.findElement(By.name("LastName")).sendKeys("Last Name");
  driver.findElement(By.name("GmailAddress")).sendKeys("GmailAddress@gmail.com");
   
 }catch(Exception e){
  //Takes the screenshot  when test fails
     File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(scrFile, new File("C:\\Users\\Public\\Pictures\\failure.png"));
   
  }
}
}


Now, we can take screenshots. However, using the above code we can take screenshot of the complete page. If in case we want to take a screenshot of a particular area. Then, we have to write a specific code for that. So, here is Java Sample code is:

Sample Java Code



public class Screenshot {

public static void main(String[] args) throws IOException {

WebDriver driver = new FirefoxDriver();
driver.get("http://aroraglobalservices.blogspot.in/");
WebElement element = driver.findElement(By.xpath("//*[@id='Header1_headerimg']"));
WrapsDriver wrapsDriver = (WrapsDriver) element;
//Get the entire Screenshot from the driver of passed WebElement
File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).
getScreenshotAs(OutputType.FILE);
//Create an instance of Buffered Image from captured screenshot
BufferedImage img = ImageIO.read(screen);
// Get the Width and Height of the WebElement using
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
System.out.println("width"+ width + "height" + height);
//Create a rectangle using Width and Height
Rectangle rect = new Rectangle(100, 100);
//Get the Location of WebElement in a Point.
//This will provide X & Y co-ordinates of the WebElement
Point p = element.getLocation();
//Create image by for element using its location and size.
//This will give image data specific to the WebElement
BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width,
rect.height);
//Write back the image data for element in File object
ImageIO.write(dest, "png", screen);
FileUtils.copyFile(screen, new File("D:\\test.png"));
}
}