Saturday, December 20, 2014

Data-Driven Test case failure take a screenshot with Selenium WebDriver using TestNG




Because with one look at the screenshot we can get an idea of where exactly the script got failed.

Here is the sample code to take screenshot of webpage

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  

 FileUtils.copyFile(scrFile, new File("D:\\failurescreenshot.png"));  

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 By.name("signin")  actual is By.name("signIn").


Excel sheet



Source code:
import java.io.File;
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
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.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

       public class Failurescreenshot {
        private WebDriver driver;
        
        @BeforeClass
        public void Startup() {
         driver = new FirefoxDriver();
        }
        @Test(description = "Read Gmail account")
        public void Login() throws Exception {
         FileInputStream fi = new FileInputStream("D:\\testmail.xls");
         Workbook w = Workbook.getWorkbook(fi);
         Sheet s = w.getSheet(0);
         driver.get("http://www.gmail.com");
         try {
          for (int i = 1; i < s.getRows(); i++) {
           // Read data from excel sheet
           String s1 = s.getCell(0, i).getContents();
           String s2 = s.getCell(1, i).getContents();
           driver.findElement(By.name("Email")).sendKeys(s1);
           driver.findElement(By.name("Passwd")).sendKeys(s2);
           driver.findElement(By.name("signin")).click();
           Thread.sleep(9000);
          }
         } catch (Exception e) {
                System.out.println(e);
                File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
                FileUtils.copyFile(scrFile, new File("D:\\failurescreenshot.png")); 
         }
        }

        @AfterClass
        public void teardown() {
         driver.quit();
        }

}


Taken Screenshot



signIn webelement is not found..


Hope you like this post

Hit Like button on Facebook.








1 comment:

  1. This is the best explanation I have seen so far on the web. I was looking for a simple yet informative about this topic finally your site helped me a lot to gain knowledge.
    Selenium Training Chennai
    software testing selenium training

    ReplyDelete