Testing with the Robot
Problem
You want to
simulate the user clicking
on the mouse or typing with the keyboard using
java.awt.Robot.
Solution
We do not recommend this technique.
Discussion
java.awt.Robot allows Java applications to take
command of native system input events, such as moving the mouse
pointer or simulating keystrokes. At first glance, this seems to be a
great way to test your GUIs. Your tests can do exactly what the user
might do and then verify that your components are displaying the
correct information.
We have found that this approach is dangerous.
Robot tests are very fragile, breaking any time the GUI layout changes.
If the user moves the mouse while the tests are running, the Robot continues clicking, sometimes on the wrong application.[28]
Since the tests run so quickly, it can be impossible to stop the tests once the Robot gets confused and starts clicking on other apps and typing characters that show up in other windows.
If you really feel that you could use some Robot tests, consider
naming them differently than other tests. You might have a collection
of RobotTest*.java tests. You can then run them
independently of other tests, if you are extremely careful to avoid
touching the mouse while the tests run.
See Also
Chapter 11 provides some references to Swing-specific testing tools.
[28] One programmer reported that the Robot sent a partially completed email because it clicked on the send button of the mail client instead of a button in the application being tested. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access