Test Overview
This test checks how to handle the StaleElementReferenceException in Selenium Java. It verifies that the test retries finding an element if it becomes stale after a page update.
This test checks how to handle the StaleElementReferenceException in Selenium Java. It verifies that the test retries finding an element if it becomes stale after a page update.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.StaleElementReferenceException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class StaleElementHandlingTest { WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); driver.get("https://example.com/dynamic"); } @AfterEach public void tearDown() { driver.quit(); } @Test public void testHandleStaleElement() { WebElement dynamicText = driver.findElement(By.id("dynamic-text")); WebElement button = driver.findElement(By.id("refresh-btn")); button.click(); int attempts = 0; while (attempts < 3) { try { String text = dynamicText.getText(); assertEquals("Updated Text", text); break; } catch (StaleElementReferenceException e) { dynamicText = driver.findElement(By.id("dynamic-text")); attempts++; } } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser opened at https://example.com/dynamic | - | PASS |
| 2 | Find element with id 'refresh-btn' | Button element located on page | - | PASS |
| 3 | Click the 'refresh-btn' button to update page content | Page content starts updating dynamically | - | PASS |
| 4 | Try to find element with id 'dynamic-text' and get its text | Element may be stale due to page update | Check if element text equals 'Updated Text' | FAIL |
| 5 | Catch StaleElementReferenceException and retry finding element | Element reference refreshed after retry | Check if element text equals 'Updated Text' | PASS |
| 6 | Assertion passes confirming text is 'Updated Text' | Test confirms updated page content | assertEquals("Updated Text", text) | PASS |
| 7 | Test ends and browser closes | Browser closed | - | PASS |