Tech Blog

Testing

The Complete Guide: How to Take a Screenshot using Selenium Java

By Lokesh Sontakke4 min read
← Back to blog

In the real-world scenario, test execution takes place on some remote server 24×7 and no one monitors test execution with bare eyes. knowing what is not working or failing becomes more challenging. The Screenshot helps us to know the cause of the failure. It can be used in reporting a bug and finding the exact issue. 

We can take screenshots of webpage or WebElement using Selenium. Using TestNG listeners we can take screenshots of webpages on certain events like test case failure. That is during test script execution if something fails then it will automatically take a screenshot of that webpage and store it in a specific folder of the project. 

Here are some important cases in which Selenium screenshots would be required:

1.  When Web console issues occur.
2.  When an assertion condition fails.
3.  When web element Xpath value is not proper on a WebPage.
4.  Where there is a Timeout in finding web elements on a web page.

1. Take a screenshot of a Webpage using Selenium Java and TestNG

 getScreenshotAs = is a method to create an image file in jpg, png format which is provided by the TakesScreenshot interface to capture the screenshot of the web page displayed in the driver object.

 TakesScreenshot = TakeScreenshot is a selenium java interface. we can’t create an object directly. We have to convert the webdriver object to TakesScreenshot.

Below is the demo code for taking screenshot of the Webpage

public class WebElementScreenshot {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = WebDriverManager.chromedriver().create();}
@AfterMethod
public void teardown() {
driver.quit();
    }
@Test
void testScreenshotPng() throws IOException {
    driver.get(“https://google.com“);
    TakesScreenshot ts = (TakesScreenshot) driver;
    File screenshot = ts.getScreenshotAs(OutputType.FILE); 
    Path destination = Paths.get(“screenshot.png”); 
    Files.move(screenshot.toPath(), destination, REPLACE_EXISTING); 
}

    1.    We make the browser screen a PNG file.

    2.    This file is located in a temporary folder by default, so we move it to a new file called screenshot.png (in the root project folder).

    3.    We use standard Java to move the screenshot file to the new location.

2. Take a screenshot of a specific WebElement using Selenium Java code

Below is the demo code for taking screenshot of the Webpage

public class TestScreenshotTestNg {
        WebDriver driver;
        @BeforeMethod
        public void setup() {
            driver = WebDriverManager.chromedriver().create();
        }
        @AfterMethod
        public void teardown() {
            driver.quit();
        }
        @Test
        public void testWebElementScreenshot() throws IOException {
            driver.get(
                    “https://www.myntra.com/”);
            WebElement form = driver.findElement(By.tagName(“form”));
            File screenshot = form.getScreenshotAs(OutputType.FILE);
            Path destination = Paths.get(“webelement-screenshot.png”);
            Files.move(screenshot.toPath(), destination, REPLACE_EXISTING);
        }

3. Take a screenshot of a webpage on test failure using Selenium Java, TestNg, and Maven

   Add the below dependencies in the maven project POM XML.

 <dependencies>
    <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
           <version>2.11.0</version>
     </dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.0.3</version>
</dependency>
    <dependencies>

Below is the demo code to take a screenshot of the Webpage on test case failure.

public class FailTestCases {
protected WebDriver driver;
@BeforeClass
public void setUp(){
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(); 
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(60));
driver.get(“https://www.google.com/”);
Reporter.log(“Launched myntra Portal Successfully”);
}
@AfterClass
public void tearDown() throws InterruptedException{
sleep(2);
driver.quit();
}
public void sleep(int seconds) throws InterruptedException
                {
int milliseconds = seconds*1000;
Thread.sleep(milliseconds);
  }
@Test(priority = 1)
public void clickbtn() throws InterruptedException {
driver.get(“https://www.myntra.com/”);
By searchbox = By.xpath(“//input[@title=’Search’]”);
driver.findElement(searchbox).click();
}
@AfterMethod
public void recordFailure(ITestResult result){
if(ITestResult.FAILURE == result.getStatus())
{
var camera = (TakesScreenshot)driver;
File screenshot = camera.getScreenshotAs(OutputType.FILE);
try{
FileUtils.copyFile(screenshot, new File(“/Users/lokesh.sontakke/eclipse-workspace/Screenshot/Screenshots2/TestcaseFailed.png”));
}catch(IOException e){
e.printStackTrace();
}
}
}
}

How can we call the driver object in TestListeners using TestNG?

Taking screenshots requires a user to have a driver object. In order to do so, one has to get the driver from ITestResult which must be configured in the AfterMethod. 

  1. In @BeforeClass we are initializing the chrome browser using selenium webDriver and launching the URL.
  2. In the @Test method, we have written test cases and run test cases using TestNG.
  3. In @AfterMethod, Call the method ‘onTestFailure’. Written a failed test case screenshot code and screenshot.png file store it in one folder.
  4. In @AfterClass, After test case execution browser gets close.

Keep reading

You may be interested in

Browse all articles →
Software Testing: Challenges and Solutions
February 8, 20244 min read

Software Testing: Challenges and Solutions

Introduction – Testing software is a crucial aspect of the development process. It makes sure that the product’s functionality works as expected, fulfills the user requirements, and makes sure it works without errors. In this blog, we will list down some of the most common challenges faced in software testing and conclude with how to […]

By Saboor ChandshahaRead More →
Streamlining Software Quality: The Power of Automating Black Box Testing
February 8, 20244 min read

Streamlining Software Quality: The Power of Automating Black Box Testing

Introduction :  In the dynamic realm of software development, ensuring the robustness and reliability of applications is of paramount importance. Black box testing, a technique that assesses software functionality without requiring knowledge of its internal code, plays a vital role in identifying potential defects. As the complexity of software systems continues to escalate, the manual […]

By Anthony Gilchrist G SRead More →
Implementing best practices for end-to-end testing in cloud migration
January 31, 20245 min read

Implementing best practices for end-to-end testing in cloud migration

Importance of End-to-End Testing Assume an organization’s core systems are now hosted on the cloud—a complex ecosystem linked by data threads. End-to-end testing is the foundation upon which the reliability and performance of this interconnected web is built. This rigorous testing technique makes it possible to detect vulnerabilities, optimize operations, and improve user experience. Active […]

By Rahul ChakravartiRead More →