HowTo: Add all controls on a page to the UI Map
One of the most frequent asks in Coded UI Test Forums is the ability to add all controls on a page to the UI Map. This can be done with the following code snippet. Here I am adding all controls on the bing start page to the specified ui test file.
[TestMethod]
public void CodedUITestMethod1()
{
string uiTestFileName = @"D:\dev11\ConsoleApplication1\TestProject1\UIMap.uitest";
UITest uiTest = UITest.Create(uiTestFileName);
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap();
newMap.Id = "UIMap";
uiTest.Maps.Add(newMap);GetAllChildren(BrowserWindow.Launch(new Uri("https://bing.com")), uiTest.Maps[0];);
uiTest.Save(uiTestFileName);
}
private void GetAllChildren(UITestControl uiTestControl, Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap map)
{
foreach (UITestControl child in uiTestControl.GetChildren())
{
map.AddUIObject((IUITechnologyElement)child.GetProperty(UITestControl.PropertyNames.UITechnologyElement));
GetAllChildren(child, map);
}
}
Let us look at what the code snippet does.
UITest uiTest = UITest.Create(uiTestFileName);
This line of code creates a UITest object from a file. Here I am assuming that we have an empty UITest file. You can add an empty UI Test file to your Test Project by right clicking on the Test Project and choosing Add –> New Item –> Coded UI Test Map.
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap();
newMap.Id = "UIMap";
uiTest.Maps.Add(newMap);
These 3 lines create a new UIMap object and adds it to UITest object
GetAllChildren(BrowserWindow.Launch(new Uri("https://bing.com")), uiTest.Maps[0];);
The next line launches the browser, navigates to bing.com and passes a reference to the browser & the UIMap object to GetAllChildren method. GetAllChildren recursively gets the children of the browser object and adds them to the UIMap.
In the interests of brevity and ease of description, I have not handled error & exception conditions. You can now customize the code based on your need. Instead of GetChildren, you can use FindMatchingControls to add all controls of a specific type.