Bird
Raised Fist0
Selenium Javatesting~15 mins

Clearing fields in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Clear text from input fields on a form
Preconditions (1)
Step 1: Locate the input field with id 'username' and enter the text 'testuser'
Step 2: Locate the input field with id 'email' and enter the text 'testuser@example.com'
Step 3: Clear the text from the 'username' input field
Step 4: Clear the text from the 'email' input field
✅ Expected Result: Both 'username' and 'email' input fields are empty after clearing
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify 'username' input field is empty after clearing
Verify 'email' input field is empty after clearing
Best Practices:
Use explicit waits to ensure fields are interactable before actions
Use By.id locator strategy for input fields
Use clear() method to clear input fields
Use assertions from a testing framework like TestNG or JUnit
Automated Solution
Selenium Java
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 ClearFieldsTest {
    private WebDriver driver;
    private WebDriverWait wait;

    @BeforeClass
    public void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        driver.get("https://example.com/formpage");
    }

    @Test
    public void testClearInputFields() {
        // Locate username field and enter text
        WebElement usernameField = wait.until(ExpectedConditions.elementToBeClickable(By.id("username")));
        usernameField.sendKeys("testuser");

        // Locate email field and enter text
        WebElement emailField = wait.until(ExpectedConditions.elementToBeClickable(By.id("email")));
        emailField.sendKeys("testuser@example.com");

        // Clear username field
        usernameField.clear();
        // Clear email field
        emailField.clear();

        // Assert username field is empty
        Assert.assertEquals(usernameField.getAttribute("value"), "", "Username field should be empty after clearing");

        // Assert email field is empty
        Assert.assertEquals(emailField.getAttribute("value"), "", "Email field should be empty after clearing");
    }

    @AfterClass
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

This test uses Selenium WebDriver with Java and TestNG for assertions.

In setUp(), we open the browser and navigate to the form page.

In the test method, we wait until the input fields are clickable to ensure they are ready for interaction.

We enter text into the username and email fields, then clear them using the clear() method.

Assertions check that the fields are empty by verifying their value attribute is an empty string.

Finally, tearDown() closes the browser to clean up.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() instead of explicit waits
Using incorrect locator strategies like XPath with absolute paths
{'mistake': 'Not verifying the field is empty after clearing', 'why_bad': 'Without assertions, the test does not confirm the clear action succeeded.', 'correct_approach': "Add assertions to check the input field's value attribute is empty."}
Calling clear() before the element is interactable
Bonus Challenge

Now add data-driven testing with 3 different sets of input values for username and email, then clear and verify each.

Show Hint

Practice

(1/5)
1. What is the primary purpose of the clear() method in Selenium WebDriver when working with input fields?
easy
A. To disable the input field
B. To submit the form automatically
C. To remove any existing text from the input field
D. To highlight the input field

Solution

  1. Step 1: Understand the role of clear() in Selenium

    The clear() method is designed to remove any text or value present in an input field, making it empty.
  2. Step 2: Differentiate from other actions

    Unlike submitting, disabling, or highlighting, clear() specifically empties the field content.
  3. Final Answer:

    To remove any existing text from the input field -> Option C
  4. Quick Check:

    clear() empties input fields [OK]
Hint: Remember: clear() empties fields, it doesn't submit or disable [OK]
Common Mistakes:
  • Confusing clear() with submit()
  • Thinking clear() disables the field
  • Assuming clear() highlights the field
2. Which of the following is the correct syntax to clear a text input field using Selenium WebDriver in Java?
easy
A. driver.findElement(By.id("username")).clear();
B. driver.clear(By.id("username"));
C. driver.findElement(By.id("username")).removeText();
D. driver.clearText(By.id("username"));

Solution

  1. Step 1: Identify the correct method call on the WebElement

    In Selenium Java, clear() is called on the WebElement returned by findElement().
  2. Step 2: Verify syntax correctness

    driver.findElement(By.id("username")).clear(); correctly chains findElement(By.id("username")) with clear(). Other options misuse method calls or syntax.
  3. Final Answer:

    driver.findElement(By.id("username")).clear(); -> Option A
  4. Quick Check:

    Use findElement(...).clear() to clear fields [OK]
Hint: Always call clear() on the WebElement, not on driver [OK]
Common Mistakes:
  • Calling clear() directly on driver
  • Using non-existent methods like removeText()
  • Incorrect method chaining order
3. Consider the following Java Selenium code snippet:
WebElement input = driver.findElement(By.name("email"));
input.sendKeys("user@example.com");
input.clear();
String text = input.getAttribute("value");
System.out.println(text);

What will be printed on the console after execution?
medium
A. "user@example.com"
B. "" (empty string)
C. null
D. Throws NoSuchElementException

Solution

  1. Step 1: Trace the input field actions

    The code first types "user@example.com" into the input, then clears it with clear().
  2. Step 2: Check the value after clearing

    After clearing, the input field is empty, so getAttribute("value") returns an empty string.
  3. Final Answer:

    "" (empty string) -> Option B
  4. Quick Check:

    clear() empties field, so value is empty string [OK]
Hint: After clear(), getAttribute("value") returns empty string [OK]
Common Mistakes:
  • Assuming old text remains after clear()
  • Expecting null instead of empty string
  • Confusing exceptions with normal behavior
4. You wrote the following Selenium Java code to clear a text field:
driver.findElement(By.id("searchBox")).clear;

But it throws a compilation error. What is the mistake?
medium
A. Missing semicolon at the end
B. Incorrect locator type used
C. clear() cannot be used on input fields
D. Missing parentheses after clear method call

Solution

  1. Step 1: Analyze the method call syntax

    The clear method requires parentheses to invoke it as a function: clear().
  2. Step 2: Identify the compilation error cause

    Omitting parentheses causes a syntax error because clear is a method, not a field.
  3. Final Answer:

    Missing parentheses after clear method call -> Option D
  4. Quick Check:

    Always use clear() with parentheses to call the method [OK]
Hint: Remember: methods need () to execute, not just name [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Confusing locator errors with syntax errors
  • Thinking clear() is a property, not a method
5. You want to clear a text field only if it already contains some text, to avoid unnecessary actions. Which Java Selenium code snippet correctly implements this logic?
hard
A. WebElement field = driver.findElement(By.id("input1")); if (!field.getAttribute("value").isEmpty()) { field.clear(); }
B. WebElement field = driver.findElement(By.id("input1")); if (field.getText() != null) { field.clear(); }
C. WebElement field = driver.findElement(By.id("input1")); if (field.getAttribute("text") != "") { field.clear(); }
D. WebElement field = driver.findElement(By.id("input1")); if (field.getValue() != null) { field.clear(); }

Solution

  1. Step 1: Identify correct way to get input field value

    Input field text is accessed via getAttribute("value"), not getText() or getValue().
  2. Step 2: Check for non-empty string before clearing

    WebElement field = driver.findElement(By.id("input1")); if (!field.getAttribute("value").isEmpty()) { field.clear(); } checks if the value is not empty using isEmpty() and then calls clear().
  3. Final Answer:

    Option A correctly checks and clears the field only if it has text -> Option A
  4. Quick Check:

    Use getAttribute("value") and check isEmpty() before clear() [OK]
Hint: Check getAttribute("value") for text before clearing [OK]
Common Mistakes:
  • Using getText() to read input field value
  • Comparing strings with != instead of equals or isEmpty()
  • Using non-existent getValue() method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard