Automation Testing has defined a new faucet of modern day testing and it is here to stay. However if the testing process fails, it would be highly inconvenient to re-test the entire script. This is where screenshots come in handy, as they help detect test failures instantly. Through the medium of this blog we will learn how to take a screenshot in Selenium WebDriver.

I’ll be discussing the following topics:

So, let’s get started, folks!

Screenshot in Selenium WebDriver: Why Screenshot is required in Automation testing?
Screenshots are desirable for bug analysis. Selenium can automatically take screenshots during execution. Suppose you write a test script to automate a web page, you would not keep monitoring to see if it’s working right every time. You would let the script do its job and you’d be occupied in some other work.
  • Screenshots help us in understanding the flow of application and checks if it is behaving accordingly.
  • You need to typecast WebDriver instance to TakesScreenshot.
  • It helps while you are performing cross-browsing testing as the user requires to view the reports of the execution
  • Tracking the execution would become much easy if you are working on a headless browser.
  • Screenshot of the tests that failed can also be easily captured.
Now, let us move ahead and learn how exactly you can take a screenshot in while testing an application.

Screenshot in Selenium WebDriver: How to capture Screenshot in Selenium?

To capture a screenshot in Selenium, we can make use of an interface, called TakesScreenshot. This method indicates the driver, that it can capture a screenshot and store it in different ways.

Syntax:

 File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String screenshotBase64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64); 
where OutputType defines the output type for a screenshot.
In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs
Let’s understand this in detail
For WebDriver extending TakesScreenshot method, this makes the best effort depending on the browser to return the following in a preferable order:
  • The entire page
  • Current window
  • Visible portion of the current frame
  • A screenshot of the entire display containing the browser
  • The entire content of the HTML element – The visible portion of the HTML element

Syntax:

  X getScreenshotAs(OutputType<X> target)  throws WebDriverException 

where

  • X is the return type of the method
  • Target holds the destination address
  • Throws WebDriverExecption if the underlying implementation does not support screenshot capturing.

Test case failed

Selenium WebDriver has come up with some great new functionalities that make testing an application much easier. This is because the WebDriver architecture allows interaction outside of Javascript sandbox. One of the new useful functionality is being able to take screenshots from the WebDriver.
You can take screenshots at any stage of the test, but mostly, it is used for when a test fails and taking screenshots helps the analysis so we can see what went wrong during a test failure. This can be done using TestNG annotations. 

To do this, first, I’ll need to

  • Create a class and then implement TestNG ‘ITestListener.
  • Then call a method ‘onTestFailure’.
  • Add the code to take the screenshot in this method.
  • Instead of just taking the screenshot, get the Test method name and take a screenshot with the test name and place it in the destination folder.

Now, the question is how to get the driver object in the TestListeners class using TestNG?

I’ll help you understand how easy it is to do that.

To take a screenshot in Selenium, we need to to have a driver object. Get the driver from the ITestContext which has to be set in the base setup where it is easy to create our driver instance.
Hope you guys are clear with this. Moving ahead, we’ll take a look at the demo where I will help you understand how simple it is to take a screenshot in Selenium.

I will be explaining two different programs here so that you get a proper idea about how to take a screenshot in Selenium.

First program deals with how to capture a screenshot of the test case run successfully. The second program helps you understand how to take a screenshot during the test failure.

Screenshot in Selenium WebDriver: Demo

The very first thing to do when you want to test a web application is to have the Selenium Jar files and the Java libraries. You can choose an IDE of your choice. I prefer working on the Eclipse IDE because it is user-friendly.
  • I will set the browser driver to ChromeDriver.
  • Instantiate the driver instance with the ChromeDriver.
  • Get the URL of the webpage.
  • Perform corresponding actions.

In this case, I will take a screenshot of our official webpage Edureka.co.

Refer to the below code:

</pre>

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;
import org.openqa.selenium.chrome.ChromeDriver;

public class Screen {

public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:UsersNeha_VaidyaDesktopchromedriver_win32chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.edureka.co/");
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./Screenshots/Screen.png"));
System.out.println("the Screenshot is taken");
driver.quit();
}

}
<pre>

The output for the above code is depicted below:

ScreenOutput - How to take screenshot in Selenium - Edureka

And the folder contains the image

Screenshot - How to take screenshot in Selenium - Edureka

Now, let us understand how to take a screenshot of the test failed

  • First, create a Maven project.
  • Add the TestNG XML file.
  • Add the maven dependencies.
  • Create a class BaseClass which holds the WebDriver instance.
  • Define two functions namely initialization() and failed()
  • Call these two functions in another class, demo which inherits the BaseClass.
  • This Demo class holds the two methods setUp()  which calls the initialization() function, tearDown() helps in closing the driver and ScreenshotTest() where we assert the actual and the expected output.
  • In this case, I will assert both true and false which results in the failure of the test case.
  • Create another class, ListenersClass which helps the WebDriver listen to the particular events.
  • Add this code in the demo class @Listeners(ListenersClass.class) before the main function in order to listen to the test case.

You can refer to this code:

BaseClass


package com.edureka;
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;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Listeners;

public class BaseClass {
public static WebDriver driver;

public static void initialization()
{
System.setProperty("webdriver.chrome.driver", "C:UsersNeha_VaidyaDesktopchromedriver_win32chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.edureka.co/");

}
public void failed()
{
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("/C:/Users/Neha_Vaidya/eclipse-workspace/Screens/"
+ "ScreenshotsTaken/tests.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}

}

DemoClass


package com.edureka;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(ListenersClass.class)
public class demo extends BaseClass{
@BeforeMethod
public void setUp() {
initialization();

}

@AfterMethod
public void tearDown()
{
driver.quit();
}

@Test
public void takeScreenshotTest()
{
Assert.assertEquals(true, false);
}
}

ListenersClass


package com.edureka;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class ListenersClass extends BaseClass implements ITestListener{

public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub

}

public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub

}

public void onTestFailure(ITestResult result) {
System.out.println("Failed Test");
failed();

}

public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub

}

public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub

}

public void onStart(ITestContext context) {
// TODO Auto-generated method stub

}

public void onFinish(ITestContext context) {
// TODO Auto-generated method stub

}

}

The output is depicted in this manner:

TestFailedScreenshot - How to take screenshot in Selenium - Edureka

ScreenShot1- How to take screenshot in Selenium - Edureka

With this, we come to an end to this “How to take a screenshot in Selenium WebDriver” blog. I hope you guys enjoyed this article and understood how to run a test case. Got a question for us? Please mention it in the comments section of “How to take a screenshot in Selenium WebDriver” and we will get back to you.
If you wish to learn more about Selenium WebDriver and build a career in the same, then check out our Selenium Certification Course which comes with instructor-led live training and real-life project experience. This training will help you understand Selenium Testing in depth and help you achieve mastery over the subject.