What is a good approach to avoiding Selenium tests being broken when dealing with the changing "Name" and "Id" attributes of a control that is rendered on a ASP.NET page using a master page? I want to avoid changing my tests when ASP.NET renders the web page's controls with different DOM identifiers.
http://www.stevetrefethen.com/blog/AutomatedTestingOfASPNETWebApplicationsUsingSelenium.aspx
Selenium solves this problem using XPATH and providing the ability to locate controls based on XPATH expressions, alleviating the need to hard code HTML tag structure into a test script. For example, the ASP.NET runtime may render ID attributes that look like:
id="ctl00_cphContents_gridMaint_DataGrid"
Finding this control using an XPATH expression can be simplified to something like this:
table[contains(@id, "gridMaint")]
In the event the nesting of the DataGrid changes the script will continue to function properly as long as table's ID contains the text "gridMaint".
Another option is to use CSS locators. They're normally less fragile than XPath. For example, to target a div with a class of .myDiv you can use the locator "css=.myDiv". If the specified element has other classes the CSS locator will still work, although the XPath equivalent would change from "//div[@class='myDiv']" to "//div[contains(@class, 'myDiv']". Also, CSS locators tend to be faster than XPath across browsers.