Monday, July 29, 2019

How to take screenshot in selenium? | TakesScreenShot interface in selenium | How to take screenshot of a fail test in Selenium WebDriver ?

Sometimes you may have feel uncertainty when you are running you test and test goes fail than you need to capture a screenshot of your failed Test case.

Capturing screenshot in selenium is very easy. it can be done by TakesScreenshot interface.

Copy this below code and paste it in your class at the step where your test is failing.


TakesScreenshot ts=(TakeScreenshot)driver;
  File file=ts.getScreenshotAs(OutputType.FILE);
  try {
   FileHandler.copy((File) ts,new File("./screenshot/login.png"));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

Step 1:- Create a class and write the test code.

Step 2:- Paste this code where you test is failing.

Here in code, i am storing this screenshot as "login.png" but for your use you can give it other name too. i would suggest to use timestemp_filename to save the screenshot.

lets look at the code now,




package wixlogin;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;

public class Login {

 public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\eclipse-workspace\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  driver.get("http://dixitjani666.wixsite.com/mysite");
  driver.manage().window().maximize();
  driver.findElement(By.id("ggl-login-text")).click();
  driver.findElement(By.xpath(".//*[@id='view_container']/form/div[2]/div/div/div[1]/ul/li[2]/div")).click();
 
  TakesScreenshot ts=(TakeScreenshot)driver;
  File file=ts.getScreenshotAs(OutputType.FILE);
  try {
   FileHandler.copy((File) ts,new File("./screenshot/login.png"));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  driver.close();
  
 }

}


Step 3:- Run this class file. when your test is get executed you will see a screenshot folder in your project folder. in that you will get the PNG file of your test.


I hope this will helpful to you :) if you guys find it helpful than please share it with others :)

Happy learning!

No comments:

Post a Comment