Submitting forms 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 ContactFormTest { 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 testSubmitContactForm() { driver.get("https://example.com/contact"); // Fill in the Name field WebElement nameField = wait.until(ExpectedConditions.elementToBeClickable(By.id("name"))); nameField.clear(); nameField.sendKeys("John Doe"); // Fill in the Email field WebElement emailField = driver.findElement(By.id("email")); emailField.clear(); emailField.sendKeys("john.doe@example.com"); // Fill in the Message field WebElement messageField = driver.findElement(By.id("message")); messageField.clear(); messageField.sendKeys("Hello, this is a test message."); // Click the Submit button WebElement submitButton = driver.findElement(By.id("submitBtn")); submitButton.click(); // Wait for the success message to appear WebElement successMsg = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("successMsg"))); // Verify the success message is displayed Assert.assertTrue(successMsg.isDisplayed(), "Success message should be displayed"); // Verify the success message text String expectedText = "Thank you for contacting us!"; Assert.assertEquals(successMsg.getText().trim(), expectedText, "Success message text should match"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test uses Selenium WebDriver with Java and TestNG to automate submitting a contact form.
Setup: We create a ChromeDriver instance and a WebDriverWait for explicit waits.
Test steps: We open the contact page URL, then locate each form field by its id. We clear any existing text and enter the test data exactly as specified.
We click the submit button, then wait explicitly for the success message element to become visible.
Assertions: We check that the success message is displayed and that its text matches the expected message.
Teardown: We close the browser after the test.
This approach uses explicit waits to avoid timing issues, uses clear locators by id, and uses TestNG assertions for clear validation messages.
Now add data-driven testing with 3 different sets of form inputs (name, email, message) using TestNG data provider.