Tuesday, 27 May 2014

How to identify all the child elements within a page in Coded UI Test (CUIT)

There are many situations where we might need to get all the elements available from within a Page, Div, Table etc. The elements can be either list of text box, checkbox, hyperlinks etc. In QTP we can do this very easily by means of ChildCount method to return the list of child within a particular object, similarly in Visual Studio 2010 Coded UI Testing we can do the same via UITestControlcollection collection and FindMatchingControls method.

Consider a scenario where you are asked to list all the Hyperlinks within a Div element of a page. Then all you have to do is follow the three simple steps
1.       Identify the Div name (It can be for e.g. HeaderContent)
2.       Pass the Div name instance object to HTML control class (Now this will have all your controls within the particular Div, note this can be anything not just hyperlink alone which we are searching)
3.       Using FindMatchingControl method, search for the control you are interested in searching for, here its hyperlink (HtmlHyperLink class in VSTS) and pass it to UITestControlCollection.
4.       Now you have the handle for getting the controls, you can now iterate through the collection and get all the matching controls value out from it. That’s it !!!

Let’s see the above operation in code

public void SearchhyperLinks()
            //Search for the Div which has the list of hyperlinks we are searching
            HtmlDiv div = new HtmlDiv();
            div.SearchProperties[HtmlDiv.PropertyNames.Name] = "HeaderContent";
            //Pass the instance of Div to HtmlControl class
            HtmlControl controls = new HtmlControl(div);
            controls.SearchProperties.Add(HtmlControl.PropertyNames.ClassName, "HtmlHyperlink");
            UITestControlCollection collection = controls.FindMatchingControls();
            foreach (UITestControl links in collection)
                //cast the item to HtmlHyperlink type
                HtmlHyperlink mylink = (HtmlHyperlink)links;
                //get the innertext from the link, which inturn returns the link value itself