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.
Practice
Solution
Step 1: Understand form submission in Selenium
Thesubmit()method is designed specifically to submit forms in Selenium.Step 2: Differentiate from other methods
Methods likeclick()simulate clicking but do not necessarily submit forms;sendKeys()inputs text;getText()retrieves text.Final Answer:
submit() -> Option AQuick Check:
Form submission method = submit() [OK]
- Using click() instead of submit() to send form
- Confusing sendKeys() with form submission
- Trying to submit without locating form element
Solution
Step 1: Locate the form element correctly
UsefindElement(By.id("formId"))to get the form element by its ID.Step 2: Call submit() on the form element
Callingsubmit()on the form element sends the form data.Final Answer:
driver.findElement(By.id("formId")).submit(); -> Option AQuick Check:
Correct syntax = driver.findElement(...).submit() [OK]
- Trying to call submit() directly on driver
- Using click() instead of submit() on form
- Sending keys 'submit' instead of calling submit()
WebElement input = driver.findElement(By.name("username"));
input.sendKeys("user1");
input.submit();Solution
Step 1: Identify element and actions
The code finds an input field named "username", enters "user1" text, then callssubmit()on that input element.Step 2: Understand submit() behavior on child elements
Callingsubmit()on any child element inside a form submits the entire form containing that element.Final Answer:
The form containing the input field is submitted with 'user1' as username. -> Option CQuick Check:
submit() on input submits parent form [OK]
- Thinking submit() only works on form elements
- Expecting submit() to clear input instead of submitting
- Assuming submit() throws exception on input elements
WebElement form = driver.findElement(By.id("loginForm"));
form.click();
form.submit();What is the main issue with this code?
Solution
Step 1: Analyze click() on form element
Callingclick()on a form element is unusual and may trigger unexpected UI behavior or errors.Step 2: Confirm submit() usage
Callingsubmit()on the form element is correct and will submit the form.Final Answer:
Calling click() on the form element may cause unexpected behavior before submit. -> Option DQuick Check:
click() on form is risky; submit() is correct [OK]
- Thinking submit() cannot be called on form
- Assuming click() is needed before submit()
- Ignoring potential side effects of clicking form
id or name attribute but contains a submit button with class "submit-btn". Which Selenium Java code correctly submits the form?Solution
Step 1: Locate the submit button by class
Since the form lacks id or name, find the submit button using its class "submit-btn".Step 2: Call click() on the submit button element
Callingclick()on the submit button simulates pressing the button, which submits the form.Final Answer:
driver.findElement(By.className("submit-btn")).click(); -> Option BQuick Check:
click() on submit button triggers form submission [OK]
- Using submit() instead of click() on submit button
- Trying to submit form by tagName without verifying uniqueness
- Calling submit() on button tag which may not be inside form
Ready to prove it?
Pass the test and this pattern moves unknown
