i

Selenium Step By Step Guide

Capture Screenshots and Email test results

Screenshots have become a vital and essential thing when any test needs to capture a failure moment or to take a specific page's screenshot. We have various situations where capturing screenshot is required.

We can take a simple example of achieving a capture screenshot task for the home page of https://selflearning.io/  web page.

The first step here is to typecast the WebDriver type to TakesScrenshot type to achieve the screenshot capture operation. Let us see how we do that!

TakesScreenshot scr=(TakesScreenshot)driver;

Now we have to store the screenshot in a File object by using the TakesScreenshot object. We use the getScreenshotAs() method of TakesScreenshot to capture the screenshot of a page.

File screenshotFile=scr.getScreenshotAs(OutputType.FILE);

Now we have a screenshot captured by File object, and this needs to be saved at a destination, so we create one more file object as a destination to copy the screenshot into it.

File outputFile= new File("C:\\Users\\test.jpeg ");

Next step is to copy file to destination path as set by outputFile object. CopyFile() method of  FileUtils class can be used to copy the file into the destination. FileUtils class can be imported from from “import org.apache.commons.io.FileUtils

FileUtils.copyFile(screenshotFile, outputFile);

So let us now see the complete code to take the screenshot of the home page of https://selflearning.io/  web page.

package SeleniumTest.SeleniumTest;

import java.io.File;

import java.io.IOException;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.apache.commons.io.FileUtils;

public class CaptureScreenshot

{

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

    {

        System.setProperty("webdriver.chrome.driver","C:\\Users\\chromedriver.exe");

        WebDriver driver=new ChromeDriver();

        driver.get("https://selflearning.io/");

        TakesScreenshot scr=(TakesScreenshot)driver;

        File screenshotFile=scr.getScreenshotAs(OutputType.FILE);

        File outputFile= new File("C:\\Users\\test.jpeg");

        FileUtils.copyFile(screenshotFile, outputFile);

        driver.quit();

    }

}

Sending out an Email for the Test results:

We can create a TestNG project and use an Extent Report to document the test results. A failed test case captures the screenshot of the screen where the test gets failed.

We can use JavaMail API to configure the mail sending feature once the test is completed and failed test captures the screenshot of the failed page. We will see the complete code in later topic of Capture screenshot code.