Sunday, September 20, 2009

What makes a good locator

What makes a good locator?

Its ‘robust’ – i.e. small changes to the HTML structure of a page are unlikely to break the locator. Locators that are very reliant on the structure of the html are not likely to be robust.
Its ‘reliable’ – i.e. the locator is a reliable way to identify the chosen element on the page.

Suggestions

If an id exists for the chosen element, and the id looks robust (i.e. the naming of the element looks like it’s not likely to change in the future), the id is a good choice.

e.g //CalendarLink

If the page name that a link is going to is unlikely to change, then using the filename as part of the locator works well. This is likely to continue to work even if the structure of the html on a page changes. However, care needs to be taken to ensure that the element being referenced is unique on a page. The following example uses the filename of the page link together with the id of a ancestor html element to ensure the locator is reliable and robust.

e.g. //ul[@id='MySpaceNav']/li/a[contains(@href, 'MyDesktop.aspx')]


If that doesn’t exist, look at the html surrounding the element to look for a good way to describe its location which is both robust and reliable. E.g. the following locator was used to uniquely identify the ‘My Space’ link in LPv2 and used the CSS class that is always applied to the element to achieve this.

e.g. //ul/li[contains(@class, 'rm-myspacelink')]/a


If none of the above are possible, and identifier based on the location of the html element needs to be used. This is most easily discovered by using Selenium IDE and clicking on an element.


A locator type can be an element id, an element name, an xpath expression, link text, and more.
A few examples:
selenium.click(“id=idOfThing”); //an id locator
selenium.click(“name=nameOfThing”); //a name locator
selenium.click(“xpath=//img[@alt='The image alt text']”); //an xpath locator
selenium.click(“dom=document.images[40]” ); //a DOM locator
selenium.click(“link=Test Page For Selenium”); //a link locator
selenium.click(“css=span#firstChild”); //a css locator

No comments:

Post a Comment