0
0
Selenium Javatesting~10 mins

Element screenshots in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, finds a specific element, takes a screenshot of that element, and verifies the screenshot file is created successfully.

Test Code - JUnit with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ElementScreenshotTest {
    WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void testElementScreenshot() throws IOException {
        driver.get("https://example.com");
        WebElement element = driver.findElement(By.cssSelector("h1"));
        File screenshot = element.getScreenshotAs(OutputType.FILE);
        File destination = new File("element_screenshot.png");
        FileHandler.copy(screenshot, destination);
        assertTrue(destination.exists() && destination.length() > 0, "Screenshot file should exist and not be empty");
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigates to https://example.comBrowser displays the Example Domain webpage-PASS
3Finds the <h1> element using CSS selector 'h1'The <h1> element with text 'Example Domain' is locatedElement is found without exceptionPASS
4Takes screenshot of the <h1> elementScreenshot file of the element is created in memory-PASS
5Saves the screenshot file as 'element_screenshot.png'File 'element_screenshot.png' is saved on diskFile exists and file size > 0 bytesPASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: The element with CSS selector 'h1' is not found on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify after saving the element screenshot?
AThat the screenshot file exists and is not empty
BThat the entire page screenshot is saved
CThat the element is clickable
DThat the browser title matches expected
Key Result
Always verify that the element exists before taking a screenshot and confirm the screenshot file is saved and not empty to ensure the test validity.