Thursday 22 February 2018

Take Screenshot in Selenium

Take screenshot in selenium is very important for test result and bug verification.

It is very simple to take screen shot at particular moment like error page, defect etc.

First of all you have import below packages into your code.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

Now you have to create below function for take screen shot.

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;


public class TakeScreenshot
{
 public static void mTakeScreenShot(WebDriver driver, String vFileName)
 {
  try
  {
   TakesScreenshot screenShot = ((TakesScreenshot)driver);
   File srcFile = screenShot.getScreenshotAs(OutputType.FILE);
   FileUtils.copyFile(srcFile, new File("lib\\TestResult\\" + vFileName + ".png"));
   
  }
  catch(Exception E)
  {
   System.out.println("Error in take screen shot");
  }
 }

}

For highlighted part, you have to specify path to where you want to save screenshot.

Please share your inputs for this post.

How to write data into Text file in Selenium

Write data to any external source in selenium is very important when we are working with framework.
Data can be write in any format like excel, csv, text etc.


first of all you have to import below packages for apache poi.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

Now you need to create separate function for write data into text. If file is not there at specific path then code will create first file the write data into it.



public void mWriteDataInText(String vFilePath, String[][] vData, Boolean append)

 {
  try

  {

   File file = new File(vFilePath);
  
   if(!file.exists())
   {

    file.createNewFile();

   }
   
   FileWriter fw = new FileWriter(file.getAbsolutePath(), append);

   BufferedWriter bw = new BufferedWriter(fw);

   bw.newLine();   

   for(int i=0;i<vData.length;i++)
   {

    bw.newLine();

    for(int j=0;j<vData[0].length; j++)

    {     

     bw.write(vData[i][j]);

     bw.write(" : ");     

    }       

   }

   bw.close();   

  }

  catch(Exception E)

  {

   System.out.println("Error in write data into text file.");

  }

 }
Please add comment if you have any question regarding this post.

Popular