0
0
Selenium Javatesting~10 mins

Keyboard actions (keyDown, keyUp) in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if holding down the SHIFT key while typing in an input box results in uppercase text. It verifies that keyboard actions like keyDown and keyUp work correctly.

Test Code - JUnit with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class KeyboardActionsTest {
    WebDriver driver;
    Actions actions;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        actions = new Actions(driver);
        driver.get("https://example.com/keyboard-input");
    }

    @Test
    public void testShiftKeyDownAndUp() {
        WebElement inputBox = driver.findElement(By.id("input-text"));
        inputBox.click();

        actions.keyDown(Keys.SHIFT)
               .sendKeys("hello")
               .keyUp(Keys.SHIFT)
               .perform();

        String enteredText = inputBox.getAttribute("value");
        assertEquals("HELLO", enteredText);
    }

    @AfterEach
    public void tearDown() {
        driver.quit();
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open and ready-PASS
2Navigates to https://example.com/keyboard-inputPage with input box loadedPage loaded successfullyPASS
3Finds input box element by id 'input-text'Input box is visible and interactableElement locatedPASS
4Clicks on the input box to focusInput box is focused and ready for typing-PASS
5Performs keyDown SHIFT, types 'hello', then keyUp SHIFTInput box contains typed textKeyboard actions executed correctlyPASS
6Gets the value attribute from input boxInput box value is 'HELLO'Assert that input value equals 'HELLO'PASS
7Test ends and browser closesBrowser closed-PASS
Failure Scenario
Failing Condition: Input box value is not uppercase 'HELLO' after keyDown SHIFT and typing
Execution Trace Quiz - 3 Questions
Test your understanding
What does the keyDown(Keys.SHIFT) action do in this test?
AIt clicks the input box
BIt releases the SHIFT key after typing
CIt holds down the SHIFT key so typed letters become uppercase
DIt clears the input box
Key Result
Use keyDown and keyUp actions to simulate holding and releasing modifier keys like SHIFT for accurate keyboard input testing.