Bird
Raised Fist0
Selenium Javatesting~15 mins

Typing text (sendKeys) in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Verify typing text into the search input field
Preconditions (1)
Step 1: Locate the search input field by its id 'search-input'
Step 2: Click on the search input field to focus
Step 3: Type the text 'Selenium testing' into the search input field
Step 4: Verify that the search input field contains the text 'Selenium testing'
✅ Expected Result: The search input field should contain the exact text 'Selenium testing' after typing
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the search input field contains the typed text 'Selenium testing'
Best Practices:
Use explicit waits to ensure the search input field is visible and enabled before typing
Use By.id locator for the search input field
Use assertions from a testing framework like TestNG or JUnit
Keep code readable and maintainable
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 TypingTextTest {
    private WebDriver driver;
    private WebDriverWait wait;

    @BeforeClass
    public void setUp() {
        // Set path to chromedriver if needed
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        driver.get("https://example.com"); // Replace with actual URL
    }

    @Test
    public void testTypingTextInSearchInput() {
        // Wait until the search input is visible and enabled
        WebElement searchInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("search-input")));

        // Click to focus
        searchInput.click();

        // Type text
        String textToType = "Selenium testing";
        searchInput.sendKeys(textToType);

        // Verify the input contains the typed text
        String enteredText = searchInput.getAttribute("value");
        Assert.assertEquals(enteredText, textToType, "The search input should contain the typed text.");
    }

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

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

Setup: We open the browser and navigate to the homepage URL.

Wait: We use an explicit wait to ensure the search input field with id 'search-input' is clickable (visible and enabled).

Action: We click the input to focus and then type the text 'Selenium testing' using sendKeys.

Assertion: We get the value attribute of the input and assert it matches the typed text exactly.

Teardown: We close the browser after the test.

This approach ensures the element is ready before typing and verifies the input content correctly.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() instead of explicit waits
Using incorrect locator like XPath with absolute path
{'mistake': 'Not verifying the input value after typing', 'why_bad': 'Without verification, the test does not confirm if typing actually worked.', 'correct_approach': "Assert the input field's value attribute matches the expected text."}
Not clicking the input field before typing
Bonus Challenge

Now add data-driven testing with 3 different input texts to verify typing works for each.

Show Hint

Practice

(1/5)
1. What does the sendKeys() method do in Selenium WebDriver?
easy
A. It takes a screenshot of the current page.
B. It types text into an input field on a web page.
C. It navigates to a new URL.
D. It clicks a button on the web page.

Solution

  1. Step 1: Understand the purpose of sendKeys()

    The sendKeys() method simulates typing text into input fields.
  2. Step 2: Compare with other actions

    Clicking buttons, navigating URLs, and taking screenshots are done by other methods, not sendKeys().
  3. Final Answer:

    It types text into an input field on a web page. -> Option B
  4. Quick Check:

    sendKeys() = types text [OK]
Hint: sendKeys() = typing text into fields [OK]
Common Mistakes:
  • Confusing sendKeys() with click()
  • Thinking sendKeys() navigates pages
  • Assuming sendKeys() takes screenshots
2. Which of the following is the correct syntax to type "hello" into a text input using Selenium in Java?
easy
A. driver.findElement(By.id("inputField")).sendKeys("hello");
B. driver.sendKeys(By.id("inputField"), "hello");
C. driver.findElement(By.id("inputField")).type("hello");
D. driver.findElement(By.id("inputField")).click("hello");

Solution

  1. Step 1: Locate element and use sendKeys()

    The correct way is to find the element first, then call sendKeys() on it with the text.
  2. Step 2: Check syntax correctness

    driver.findElement(By.id("inputField")).sendKeys("hello"); uses findElement and sendKeys correctly. Others use invalid methods or wrong parameters.
  3. Final Answer:

    driver.findElement(By.id("inputField")).sendKeys("hello"); -> Option A
  4. Quick Check:

    findElement + sendKeys() = correct syntax [OK]
Hint: Always find element first, then call sendKeys() [OK]
Common Mistakes:
  • Calling sendKeys() directly on driver
  • Using non-existent methods like type()
  • Passing text to click() method
3. What will be the result of the following code snippet?
WebElement input = driver.findElement(By.name("username"));
input.sendKeys("user123");
String value = input.getAttribute("value");
System.out.println(value);
medium
A. It prints an empty string
B. It prints: username
C. It throws NoSuchElementException
D. It prints: user123

Solution

  1. Step 1: Understand sendKeys() effect

    The sendKeys("user123") types "user123" into the input field.
  2. Step 2: Retrieve input value attribute

    The getAttribute("value") returns the current text inside the input, which is "user123".
  3. Final Answer:

    It prints: user123 -> Option D
  4. Quick Check:

    sendKeys() sets value, getAttribute("value") reads it [OK]
Hint: sendKeys() sets input value, getAttribute("value") reads it [OK]
Common Mistakes:
  • Expecting getAttribute("value") to return element name
  • Assuming sendKeys() throws exception without element
  • Thinking printed value is empty
4. Identify the error in the following code snippet that tries to type "admin" into a password field:
WebElement password = driver.findElement(By.id("pass"));
password.sendkeys("admin");
medium
A. Method name should be sendKeys with uppercase K.
B. The locator By.id("pass") is incorrect.
C. sendKeys cannot be used on password fields.
D. Missing driver initialization.

Solution

  1. Step 1: Check method spelling

    The method name is case-sensitive and must be sendKeys with uppercase 'K'.
  2. Step 2: Verify locator and usage

    The locator By.id("pass") is valid and sendKeys works on password fields. Driver initialization is assumed done.
  3. Final Answer:

    Method name should be sendKeys with uppercase K. -> Option A
  4. Quick Check:

    sendKeys() method name is case-sensitive [OK]
Hint: Remember exact method name: sendKeys() with capital K [OK]
Common Mistakes:
  • Typing sendkeys() with lowercase k
  • Assuming sendKeys() can't type passwords
  • Ignoring driver setup errors
5. You want to clear any existing text and then type "hello world" into a search box using Selenium in Java. Which code snippet correctly does this?
hard
A. driver.findElement(By.name("search")).sendKeys(""); driver.findElement(By.name("search")).sendKeys("hello world");
B. driver.findElement(By.name("search")).sendKeys(Keys.CONTROL + "a", Keys.DELETE); driver.findElement(By.name("search")).sendKeys("hello world");
C. driver.findElement(By.name("search")).clear(); driver.findElement(By.name("search")).sendKeys("hello world");
D. driver.findElement(By.name("search")).sendKeys("hello world");

Solution

  1. Step 1: Clear existing text properly

    The clear() method empties the input field safely before typing.
  2. Step 2: Type new text after clearing

    After clearing, calling sendKeys("hello world") types the new text correctly.
  3. Final Answer:

    driver.findElement(By.name("search")).clear(); driver.findElement(By.name("search")).sendKeys("hello world"); -> Option C
  4. Quick Check:

    Use clear() before sendKeys() to reset input [OK]
Hint: Use clear() before sendKeys() to replace text [OK]
Common Mistakes:
  • Trying to delete text with sendKeys() shortcuts incorrectly
  • Sending empty string to clear input
  • Not clearing input before typing new text
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