This tutorial will get you up and running with the Selenium WebDriver API. If you want to catch up on the Selenium basics try reading this introductory material.
What you will learn
You will learn how to mimic usage of the following HTML elements:
A link
BUTTON
checkbox
SELECT combo box
alert box
TABLE
If you want to get straight to the code, feel free to skip the article and download this github project (look for the package called selenium2).
Example Website
Suppousedly, we have built an admin panel for managing users, which looks like this:
With the following HTML code behind:
We would like to test a scenario, where:
User opens the site, enters admin panel.
User wants to filter out all admin users, so he unchecks the "Admin" checkbox.
User promotes the third user (id=3) to being a "Moderator".
User deletes the fourth user (id=4) by clicking "Remove".
Finally, user clicks the "Save" button and confirms on the alert box.
Expected Result
After the scenario admin panel should look like this:
Here is a recording of the scenario:
Unchecking the checkbox
We would like to uncheck the "Admin" checkbox:
So we lookup the INPUT with value "Admin" inside the filter-by-role DIV:
Here is a small explanation of the used selectors:
It is up to you, whether you choose XPath or CSS selectors, but sometimes one works better than the other. We will learn about it in a moment.
Selecting option in the combo box
We want to select "Moderator" for the user with id = 3:
So we find a WebElement with id role_3 and wrap it inside a Select object:
Clicking the "Remove" link
We would like to click the remove link in the fourth row (user with id = 4).
Unfortunately, we cannot use any By.id selector, so we have to choose:
We come up with a clever selector or...
We end up with foreach loops searching for the row with id = 4 and link with text "Remove".
Again, it depends on our preferences. However, I think here it is best to use some XPath goodness:
To better understand this XPath selector take a look at this explanation [click to enlarge]:
Clicking the "Save" button and confirming changes
Finally, we click the "Save" button and confirm our changes:
Clicking the button is very straightforward:
Fortunately, alert boxes are also simple to use. When we encounter the invocation of a JavaScript confirm("Save changes?"); function, we have to switch to the alert window and then accept it:
It will act like user clicked the OK button on the pop-up window. If you would like to cancel instead, use the Alert.dismiss() method.
The End
Here ends our quick tour. I hope you enjoyed learning about the Selenium WebDriver API.