In certain Selenium Automation Tests, there is a need to control keyboard or mouse to interact with OS windows like Download pop-up, Alerts, Print Pop-ups, etc. or native Operation System applications like Notepad, Skype, Calculator, etc.
Selenium Webdriver cannot handle these OS pop-ups/applications.
In Java version 1.3 Robot API was introduced 1.3 Robot API that can handle OS pop-ups/applications.
Benefits of Robot API
- Robot API can simulate Keyboard and Mouse Event
- Robot API can help in upload/download of files when using selenium web driver
- Robot API can easily be integrated with current automation framework (keyword, data-driven or hybrid)
Robot API documentation will help you to understand the basic definition, syntax and usage of all methods, and functions available in Robot API. You can view the documentation on Official Oracle website, or you can create the documentation on your local machine.
Understanding Robot API internal methods and usage
Robot API methods can be used to interact with keyboard/mouse events while doing browser automation. Alternatively Auto IT can be used, but its drawback is that it generates an executable file (exe) which will only work on windows, so it is not a good option to use.
Some commonly and popular used methods of Robot API during web automation:
- keyPress(): Example: robot.keyPress(KeyEvent.VK_DOWN) : This method with press down arrow key of Keyboard
- mousePress() : Example : robot.mousePress(InputEvent.BUTTON3_DOWN_MASK) : This method will press the right click of your mouse.
- mouseMove() : Example: robot.mouseMove(point.getX(), point.getY()) : This will move mouse pointer to the specified X and Y coordinates.
- keyRelease() : Example: robot.keyRelease(KeyEvent.VK_DOWN) : This method with release down arrow key of Keyboard
- mouseRelease() : Example: robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK) : This method will release the right click of your mouse
Sample code to automate common use cases using Robot API
- Lets take example of web site http://spreadsheetpage.com/index.php/file/C35/P10/ wherein after you click on a web element (.//a[@href=contains(text(),’yearly-calendar.xls’]) a O.S download pop-up appears.
- To handle this we use Robot class (by creating an instance of Robot Class in your code say Robot robot = new Robot()) . Robot class us present in AWT package of JDK.
- To press down arrow key of Keyboard we use (robot.keyPress(KeyEvent.VK_DOWN))
- To press TAB key of keyboard (we use robot.keyPress(KeyEvent.VK_TAB))
- To press Enter key we use (robot.keyPress(KeyEvent.VK_ENTER)).