使用 Robot API(JAVA) 的 Keypress 事件
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class KeyBoardExample {
public static void main(String[] args) {
try {
Robot robot = new Robot();
robot.delay(3000);
robot.keyPress(KeyEvent.VK_Q); //VK_Q for Q
} catch (AWTException e) {
e.printStackTrace();
}
}
}
與 Selenium
有時我們需要按任意鍵才能測試 Web 應用程式上的按鍵事件。對於在登入表單上測試 ENTER 鍵的例項,我們可以使用 Selenium WebDriver 編寫類似下面的內容
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void testEnterKey() throws InterruptedException
{
WebDriver driver=new FirefoxDriver();
Robot robot=null;
driver.get("test-url");
driver.manage().window().maximize();
driver.findElement(By.xpath("xpath-expression")).click();
driver.findElement(By.xpath("xpath-expression")).sendKeys("username");
driver.findElement(By.xpath("xpath-expression")).sendKeys("password");
try {
robot=new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
//Keyboard Activity Using Robot Class
robot.keyPress(KeyEvent.VK_ENTER);
}
}