Test Overview
This test verifies that context switching in Selenium allows the test to interact with elements inside an iframe. It checks that switching to the iframe context enables finding and clicking a button inside it.
This test verifies that context switching in Selenium allows the test to interact with elements inside an iframe. It checks that switching to the iframe context enables finding and clicking a button inside it.
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.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import org.junit.jupiter.api.*; public class ContextSwitchingTest { private WebDriver driver; private WebDriverWait wait; @BeforeEach public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } @Test public void testSwitchToIframeAndClickButton() { driver.get("https://example.com/page_with_iframe"); // Wait for iframe to be present and switch to it wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iframe1"))); // Find button inside iframe and click WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("buttonInsideIframe"))); button.click(); // Verify some result after click (e.g., a message appears) WebElement message = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("successMessage"))); Assertions.assertEquals("Button clicked!", message.getText()); // Switch back to default content driver.switchTo().defaultContent(); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser is launched with a blank page | - | PASS |
| 2 | Navigates to https://example.com/page_with_iframe | Page with iframe loaded in browser | - | PASS |
| 3 | Waits until iframe with id 'iframe1' is available and switches to it | Driver context is now inside the iframe | iframe is present and switched | PASS |
| 4 | Finds button with id 'buttonInsideIframe' inside iframe and clicks it | Button inside iframe is clicked | Button is clickable and clicked | PASS |
| 5 | Waits for success message with id 'successMessage' to appear | Success message is visible inside iframe | Message text equals 'Button clicked!' | PASS |
| 6 | Switches back to default content (main page) | Driver context is back to main page | - | PASS |
| 7 | Test ends and browser closes | Browser is closed | - | PASS |