Click actions in Selenium Java - Build an Automation Script
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 org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class ClickActionTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver executable if needed driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); } @Test public void testClickSubmitButtonNavigatesToConfirmation() { driver.get("https://example.com/form"); // Wait until Submit button is clickable WebElement submitButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("submitBtn"))); // Click the Submit button submitButton.click(); // Wait until URL changes to expected confirmation page URL boolean urlChanged = wait.until(ExpectedConditions.urlToBe("https://example.com/confirmation")); // Assert URL is correct Assert.assertTrue(urlChanged, "URL did not change to confirmation page after clicking Submit button"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test uses Selenium WebDriver with Java and TestNG for assertions.
In setUp(), we start the Chrome browser and set an explicit wait of 10 seconds.
In the test method, we open the form page URL, then wait explicitly for the Submit button to be clickable using ExpectedConditions.elementToBeClickable. This avoids timing issues.
We then click the Submit button and wait until the URL changes to the expected confirmation page URL using ExpectedConditions.urlToBe.
Finally, we assert that the URL did change correctly, ensuring the click action worked as expected.
In tearDown(), we close the browser to clean up.
This approach follows best practices: using explicit waits, proper locators, and clear assertions.
Now add data-driven testing with 3 different form URLs and verify clicking Submit navigates to their respective confirmation pages.