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.
This test opens a webpage, finds a specific element, takes a screenshot of that element, and verifies the screenshot file is created successfully.
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(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com | Browser displays the Example Domain webpage | - | PASS |
| 3 | Finds the <h1> element using CSS selector 'h1' | The <h1> element with text 'Example Domain' is located | Element is found without exception | PASS |
| 4 | Takes screenshot of the <h1> element | Screenshot file of the element is created in memory | - | PASS |
| 5 | Saves the screenshot file as 'element_screenshot.png' | File 'element_screenshot.png' is saved on disk | File exists and file size > 0 bytes | PASS |
| 6 | Test ends and browser closes | Browser window is closed | - | PASS |