My Thoughts: 2014

Thursday, March 6

On test case failure take a screenshot with Selenium WebDriver


Don't you think "A picture is worth a thousand words.." :)

It is always(at least in most of the cases :P) better to take screenshot of webpage when the test run fails.

Because 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 :P

Here is the sample code to take screenshot of webpage
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("PathOnLocalDrive")

To get screenshot on test failure , we should put the entire code in try-catch block . In the catch block make sure to copy the above screenshot code.

In my example I am trying to register as a new user. For both first and last name fields I have used correct locator element whereas for emailaddress field I have used wrong locator element i.e name("GmailAddress1").

So when I run the script , test failed and I got the screenshot with pre filled first and last names but not email address.

Here is the sample code :
import java.io.File;
import java.io.IOException;
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.BeforeTest;
import org.testng.annotations.Test;

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("GmailAddress1")).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"));
   
  }
 }
}
And here is the screenshot of webpage on test failure


Reference  :
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#taking-a-screenshot
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html

Between have a great day ...!!! :)