fx86f fx86f - 5 months ago 33
Java Question

Difference between clicking with Selenium and clicking with Robot

Is there a difference between testing perspective and not usability, on clicking elements with selenium like this:

driver.findElement(By.id("foobar")).click();

instead of using coordinates and the robot class.

Example: If an element is not clickable because of a bug, robot will not be able to click it. Will selenium be able to click it ?

Answer

Selenium tries as much as possible to emulate what a regular user can and cannot do. When you use findElement(...).click() Selenium will raise an exception if operation cannot be performed. For instance, if an element exists in the DOM but is not displayed, an exception will be raised. And note that Selenium's .click() will try to scroll elements. If you ask it to click an element that is not visible but could be visible by scroll it, Selenium will scroll to bring it into view.

Also note that Selenium will usually take the element's coordinates and perform a click at those coordinates. So the idea that a moving element will always be hit by findElement(...).click() (expressed in this answer) is incorrect. Using findElement minimizes the window between which the coordinates are acquired and the click event is sent, but it does not completely eliminate it. The reason that Selenium works with coordinates is, again, to reproduce what a user would do. The user would see the element, move the mouse to the coordinates of the element, and click on it. If the element has an transparent overlay over it, then the overlay will get the click, rather than the element. This works because Selenium clicks at the coordinates rather than send a click directly to the element that you selected with findElement.

If you are using Robot to perform the click, the stakes are roughly the same as above, with a few caveats:

  1. Trying to click moving elements is more of an issue because the window of time between acquiring the coordinates and performing the click is greater.

  2. Robot does not know how the DOM is structured so won't scroll elements for you.

Rogério Peixoto pointed out that you can use JavaScript to perform the click. This will cause the event handler for click to be called for the element, irrespective of whether a user would be in fact able to access the element. This can allow clicking on elements that are not otherwise clickable but I would not do this unless there are overriding reasons to do so. I've gone over the difference between Selenium's click and the JavaScript click in this answer.