The attached sample utility adds support for XPath query to Coded UI Test for searching controls. The utility uses built-in XPath parser and other classes of .NET and as such is conformant to .NET’s XPath Syntax. The new utility assembly adds two extension methods to UITestControl class –
public static UITestControl FindFirstByXPath(this UITestControl controlToSearchUnder, string xPathQuery)public static IEnumerable<UITestControl> FindAllByXPath(this UITestControl controlToSearchUnder, string xPathQuery)
To use these methods, unzip the attached sample and add reference in your Coded UI Test project to the UITestXPathUtility.dll. (Note that you have manually ensure this dll is there on all machines on which the tests are run.)
Some examples of how to use these functions are –
// Get all the radio buttons in the calculatorvarvar radionButtons = calc.FindAllByXPath("//RadioButton");// Get all the radio buttons which are either Selected or have name Radians.// Note that Coded UI Test does not have built-in support for OR operator and// neither does it allow using Selected property in search condition.varvar selectedButtons = calc.FindAllByXPath("//RadioButton[@Selected != 'False' or @Name = 'Radians']");// Get the first control that has Selected property (irrespective of its value)varvar controlWithSelectedProperty = calc.FindFirstByXPath("//*[@Selected");
XPath is very powerful and expressive – I have not tested for all syntax but the way implementation is I believe all syntax would be supported. In implementation, I am not parsing or doing anything specific to XPath grammar but rather providing navigation capability via XPathNavigator interface to standard .NET APIs to support XPath.
Before using the sample further, note the two limitations\issues here –
Because of the above two limitations\issues, this should not be used as a widespread replacement of the built-in search. You should use it with prudence at places where you really need ease of use and power of XPath. I would suggest limiting the usage to places where control tree is not deep to overcome the performance penalty.
Gautam