Test Overview
This test opens a webpage, tries to find a button, clicks it, and verifies the page title. If the test fails, it takes a screenshot and saves it for debugging.
This test opens a webpage, tries to find a button, clicks it, and verifies the page title. If the test fails, it takes a screenshot and saves it for debugging.
import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; 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.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; public class ScreenshotOnFailureTest { private WebDriver driver; @Before public void setUp() { driver = new ChromeDriver(); } @Test public void testButtonClickAndTitle() throws IOException { driver.get("https://example.com"); WebElement button = driver.findElement(By.id("start-button")); button.click(); String title = driver.getTitle(); try { Assert.assertEquals("Expected Page Title", title); } catch (AssertionError e) { takeScreenshot("failure_screenshot.png"); throw e; } } private void takeScreenshot(String fileName) throws IOException { File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(srcFile, new File(fileName)); } @After 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.com homepage | - | PASS |
| 3 | Finds element with id 'start-button' | Button element is located on the page | - | PASS |
| 4 | Clicks the 'start-button' | Page reacts to button click, possibly navigates or updates | - | PASS |
| 5 | Gets the page title after click | Page title is retrieved | - | PASS |
| 6 | Checks if page title equals 'Expected Page Title' | Title is compared to expected string | Assert.assertEquals("Expected Page Title", title) | FAIL |
| 7 | On assertion failure, takes screenshot and saves as 'failure_screenshot.png' | Screenshot file is created in test folder | - | PASS |
| 8 | Test ends and browser closes | Browser window is closed | - | PASS |