How To Capture Test Case Screenshot With Selenium Webdriver

We all know it is very helpful to capture screenshots for test cases, especially for failed test cases. It is also very helpful for developers or testers to identify and debug bugs when seeing screenshots besides exception messages. We can benefit from the following points.

1. Benefits For Taking Screenshots For Test Cases.

1.1 Check why the test case failed.

If the failure reason is because of a selenium script issue such as web element locator changed, we should update our selenium script in this test case. If the failure reason is because of a program coding issue, we should provide developer or tester with the screenshot to help them to investigate.

1.2 Make a better understanding of the application’s flow and check whether the test case behaved correctly or not.

With a screenshot, you can easily know which page should be shown after login action for a system, whether the page is correct or not. You can also know which condition will direct the user to a reset password page or to a login error page. You will be more clear with each step in test cases.

1.3 Helpful when run test cases across multiple browsers(Firefox, Chrome, IE).

As you know, the test case runs differently across multiple browsers, especially the web UI part. With a screenshot, you can see the difference between multiple browsers more directly. You can save a lot of time and effort.

1.4 Track test execution process when run test cases using Headless web browser.

Test cases will run more quickly and less resource consumption with a headless web browser. You can capture the key screenshot when run test cases in a headless browser to verify the test execution process.

2. How To Capture Screenshot Using Selenium Webdriver.

Initiate Firefox webdriver instance. Maximize the Firefox browser and get http://www.google.com webpage.

 WebDriver driver = new FirefoxDriver();
 driver.manage().window().maximize();
 driver.get("http://www.google.com");

Use TakesScreenshot class’s getScreenshotAs method to get the selenium Firefox web browser screenshots.

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

Below is the example eclipse maven project file structures.

> tree /F ./
│   pom.xml
│   screenshot.png
├───src
│   ├───main
│   │   ├───java
│   │   │   └───com
│   │   │       └───dev2qa
│   │   │           └───webdriver
│   │   │               │   CaptureScreenshots.java

You need to create an eclipse maven project and create a class src\main\java\com\dev2qa\webdriver\CaptureScreenshots.java in it. Below is the CaptureScreenshots.java file content.

package com.dev2qa.webdriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;


public class CaptureScreenshots {
    
    public static void CaptureScreenshots() {
        
        try {
            
            // Because we use Firefox to communicate through the proxy server so add some Firefox options.
            FirefoxOptions firefoxOptions = new FirefoxOptions();
       
            // Avoid the Warning: Potential Security Risk Ahead error when use Firefox to get the har file. 
            // It can also avoid the unsecured massage page when use google chrome to invoke the BrowserMob proxy server.
            // firefoxOptions.setAcceptInsecureCerts(true);
            
            // Because Firefox use the geckodriver, so set the geckodriver.exe path to the system property webdriver.gecko.driver's value.
            System.setProperty("webdriver.gecko.driver", "C:\\WorkSpace\\Tool\\geckodriver-v0.29.1-win64\\geckodriver.exe");
                    
            // Create the FirefoxDriver object with the above FirefoxOptions object and start the Firefox web browser.
            WebDriver driver = new FirefoxDriver(firefoxOptions);
            
            // Maximize the Firefox web browser window.
            driver.manage().window().maximize(); 
            
            // Browse the URL in the Firefox.
            driver.get("http://www.google.com");
            
            // Convert the Firefox WebDriver object to TakesScreenshot object. 
            TakesScreenshot takesScreenshot = (TakesScreenshot)driver;
            
            // Get the screenshot image File object.
            File srcFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
            
            // Print out the screenshot image temporary saved path.
            System.out.println(srcFile.getAbsolutePath());
            
            // Create a FileInputStream object to read the above temporary image file.
            FileInputStream fis = new FileInputStream(srcFile);
            
            // Create a FileOutputStream object to write the above temporary image file.
            FileOutputStream fos = new FileOutputStream("./screenshot.png");
            
            // Define a byte array to save read byte from the temporary screenshot image file. 
            byte[] data = new byte[1024];
            
            // Read 1024 bytes from the screenshot image file.
            int num = fis.read(data);
            
            // If not read the end of the file.
            while(num > -1) {
                
                // Write the read data to the output image file.
                fos.write(data);
                
                // Read more data from the screenshot image file.
                num = fis.read(data);
                
            }
            
            // Close both FileOutputStream and FileInputStream object.
            fos.close();
            
            fis.close();
            
            System.out.println("Take screenshot complete.");
            
            // Close the Firefox web browser.
            driver.close();
            
            System.out.println("Firefox closed.");
            
        }catch(Exception ex) {
            ex.printStackTrace();
        }

    }
        

    public static void main(String[] args) {
        
        CaptureScreenshots.CaptureScreenshots();

    }

}

Below is the pom.xml file content.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>2021JavaMavenProject</groupId>
  <artifactId>2021JavaMavenProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
  
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>
    
  </dependencies>
</project>

But how can you take multiple screenshots in test cases, if you are interesting please comments to this article, then I will continue to write more.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.