Coded UI Test script to get all controls on a web page
This is something I wish i’d had a while ago.
I found this blog post:
Here’s the info from the page so I have a backup copy in case that blog post above ever gets deleted
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("http://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.
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.
UITest uiTest = UITest.Create(uiTestFileName);
These next 3 lines create a new UIMap object and adds it to UITest object
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap(); newMap.Id = "UIMap"; uiTest.Maps.Add(newMap);
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.
GetAllChildren(BrowserWindow.Launch(new Uri("http://bing.com")), uiTest.Maps[0];);
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.
Hopefully this will help others out there.
Be warned though, it can take a fair bit of time to gather all the controls on the page. So using FindMatchingControls might help as you really don’t need it to gather every single control on a page.