Using regular expressions to locate controls in Coded UI Test

When testing UI applications, you often want to locate a control on the app under test that has dynamic properties. For instance, when you login into a website, there may be a link/label on the first page that says “Welcome user, UserName1”. Now this username is going to change as per the user that logged in.

While writing a coded UI test to locate this label however, the search properties are set to the value that was found during recording. While playing back if you logged in as a new user, the search fails since it was looking for “UserName1” instead of your logged in “UserName2”. To address this, you can tweak the search properties of the control you are using:

UITestControl lblObj = new UITestControl();
lblObj.SearchProperties.Add("InnerText", "Welcome", PropertyExpressionOperator.Contains);

The above code uses “Contains” to ensure that it is searching for a string containing the substring “Welcome”. If you need a more accurate search, you might want to use regular expressions for matching the title. Unfortunately, we don’t have built in support to match the a search property against a given regular expression. However, you can write code to find the set of labels that are under a given hierarchy and match each of their inner text properties against a regular expression of your choice using the standard .NET APIs