The outcome of web tests is largely based on the presence or absence of a particular element on a page. This tight coupling to the page makes the tests very sensitive to changes in the page control hierarchy, or to content changes in general. The question is how can we break this dependency, or at least minimize the effort of updating the tests when changes in the user interface do occur. In my mind, the most robust way to verify the presence of elements on a page is through xpath. However, one challenge is that not all developers are comfortable with xpath. In this article I will introduce a helper library that will help developers create xpath expressions without even knowing anything about xpath.
The name of the library is xPathItUp.
The whole concept of xPathItUp is to let developers create xpath expressions through a fluent C# api.
Take the following xpath expression: //a[@href='http://test.test.com'] This xpath expression will locate an anchor tag with a href attribute = http://test.test.com. Xpath syntax is somewhat clunky and hard to remember, but this is where xPathItUp comes in handy:
Here's how to express the previous expression using xPathItUp:
There is also support for finding elements based on ancestors and contained text:
will find an anchor tag inside a div, inside another div.
To find an element containing a specified string you can do the following:
As you may have guessed, this lets you find an anchor tag containing the text "Home Page"
So how can we use this in web tests?
Code listing 1 shows how you can integrate the output of the XpathExpression into Selenium web tests.
Code listing 1
Selenium's IsElementPresent method supports xpath based element locators, so all you have to do is plug in the output from xPathItUp.
It this article has made you curious about xPathItUp, you may download it from: