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


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.

Leave A Comment

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