Hand Coding Coded UI Test using Visual Studio 2013

Posted by: Gouri Sohoni , on 11/18/2014, in Category Visual Studio
Views: 71274
Abstract: Code can be hand written in CUIT without the help of any code generator for Coded UI Test. In this article, we will see how to hand code Coded UI Test using Visual Studio 2013.

Coded UI Tests (CUIT) in Visual Studio are used for testing the functionality of UI controls. Creating a CUIT is easy with the use of Coded UI Test Builder. In my previous articles I have shown the use of CUIT Builder. The alternate way is to convert the manual recordings created with Microsoft Test Manager in Coded UI Test. Using CUIT Builder and the editor makes it easier to record and do any customizations to the recorded steps.

 

In one of the articles I have also discussed how to customize and re-use the code generated by CUIT Builder. But in none of these articles have I explained how to write code from scratch. In this article, I will explain how code can be hand written in CUIT without the help of any code generator for Coded UI Test.

A valid question is why to do Hand Coding for Coded UI Test when powerful code generators exist? Well we may use the hand coding option when we want to add a new action(s) on existing controls or edit the recorded action. We can also use this in order to refine our search criteria.

In order to understand how to write complete code, we need to understand the “Microsoft.VisualStudio.TestTools.UITesting.UITestControl” class. This is defined in the namespace “Microsoft.VisualStudio.TestTools.UITesting”. The assembly can be found at “system drive\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PublicAssemblies\” with the name as “Microsoft.VisualStudio.TestTools.UITesting.dll”

When we create a project based on the template for “Coded UI Test Project”, the reference to assembly gets automatically added. The namespace also provides classes to perform keyboard and mouse operations required for the controls.

The class “UITestControl” provides a way to locate any control on the User Interface. It provides many properties and methods for the control. The controls can be on Windows Forms, WPF or HTML page controls. Normally Coded UI Test finds any control by using searching and filtering. The easiest way is to search based on the Id of the control. We can also use other search options like Inner Text, Title, Class Name etc. to locate controls. Similarly we can also use filter properties, on similar lines as that of search properties. Please note that Id and Name are the properties which cannot be added to filter properties.

While searching with CUIT, all properties given in Search Properties list are evaluated first. In simple terms an AND condition of all search properties is done. In case a single control is found, CUIT will skip filter properties as there is no need of filter then. In case no control is found with search properties, the filter will still be skipped as there is no control on which the filter will be applied. Considering this we need to provide search and filter properties so as to uniquely identify the control.

Let us start with a simple example of creating a test for the following functionality – Start browser, Enter URL and Click a link on the page.

1. Create a project of type CUIT Test Project and give it a proper name.

2. Click on Cancel for the CUIT Builder as we are neither using CUIT Builder nor going to use an existing action recording

cuit-builder

3. Change the default class name to “CUITHandcoding” and also click on Yes to rename the project references.

4. Let us add some code for starting the Browser.

BrowserWindow browser = BrowserWindow.Launch(http://www.ssgsonline.net);

This line will start the browser window and also the URL for the web site as specified.

5. We can also specify if the browser will be started in state maximized state.

browser.Maximized = true;

maximized-browser

Observe that there are a few hyperlinks seen.

6. In order to click on one of the hyperlinks programmatically we will have to create an object of type UITestControl

UITestControl uiLinkAboutUs = new UITestControl(browser);

The instance creation requires an argument where we can provide the container for locating the control. In this case, the parent of the control to be located is the browser itself.
An explicit call to Find() is not required as any time if we access the control, it will result in an implicit call to find().

7. Provide the type of technology used:

uiLinkAboutUs.TechnologyName = "Web";

8. Now we need to provide search criteria so that the link for AboutUs will be located:

uiLinkAboutUs.SearchProperties.Add("ControlType", "Image");
uiLinkAboutUs.SearchProperties.Add("Id", "Image62");

9. Add the code to click on the control.

10. Playback.Wait is used to wait for certain milliseconds. It internally calls Thread.Sleep()

11. In order to find out properties of the control like Id, type of control etc.,  we can use CUIT Builder to spy the objects. Start browser and enter URL for which you need to provide steps. Start CUIT Builder by right clicking in the empty area for the method and select Generate Code for Coded UI Test – Coded UI Test builder. Once the CUIT Builder is visible, drag and drop the cross hair (used for assertions) on the object you need to find information about. In the following diagram I have used spy for “About US”

cuit-spy-object

Observe the Id, Control type, Technology name, Name for the object.

12. The complete method is as follows:

[TestMethod]
public void StartURL()
{
     BrowserWindow browser = BrowserWindow.Launch("http://www.ssgsonline.net");
     browser.Maximized = true;

     UITestControl uiLinkAboutUs = new UITestControl(browser);
     uiLinkAboutUs.TechnologyName = "Web";
     uiLinkAboutUs.SearchProperties.Add("ControlType", "Image");
     uiLinkAboutUs.SearchProperties.Add("Id", "Image62");
     Mouse.Click(uiLinkAboutUs);
     Playback.Wait(1000);

     browser.Close();
}

13. We can remove the browser launching and closing from each test method and add it as a part of Test Initialize and Test Cleanup methods. Every time any test method starts, the browser will be launched and closed at the end.

BrowserWindow browser;
//Use TestInitialize to run code before running each test 
[TestInitialize()]
public void MyTestInitialize()
{
      browser = BrowserWindow.Launch("http://www.ssgsonline.net");
       browser.Maximized = true;
 }

//Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
    browser.Close();
}

14. I am going to add a method from where we will change URL to another web site. On the url home page of www.ssgsonline.net towards the bottom, there is a sentence which says “To read all articles visit https://www.dotnetcurry.com/BrowseArticles.aspx?CatID=60”. I am going to select this url and continue. I will find out more about the control by using a similar technique of using CUIT Builder.

The code is as follows:

UITestControl uiChgUrl = new UITestControl(browser);
uiChgUrl.TechnologyName = "Web";
uiChgUrl.SearchProperties.Add("ControlType", "Cell");
uiChgUrl.SearchProperties.Add("InnerText", "To read all articles visit 
https://www.dotnetcurry.com/BrowseArticles.aspx?CatID=60");
string ChangeStr = uiChgUrl.GetProperty("InnerText").ToString();
string[] words = ChangeStr.Split(' ');
int ctr=0;
for (int i = 0; i < words.Length; i++)
{
  if (words[i].Contains("http"))
  {
     ctr=i;
     break;
  }
}

browser = BrowserWindow.Launch(words[ctr]);

Observe that this is some C# code that separates a particular string starting from http. The method can be reused whenever required.

15. When we execute the complete method, it will start one web site and later change to another, based on the url supplied.

[TestMethod]
   public void ChangeURL()
   {
      StartURL();
      UITestControl uiChgUrl = new UITestControl(browser);
      uiChgUrl.TechnologyName = "Web";
      uiChgUrl.SearchProperties.Add("ControlType", "Cell");
      uiChgUrl.SearchProperties.Add("InnerText", "To read all articles   
      visit https://www.dotnetcurry.com/BrowseArticles.aspx?CatID=60");
       string ChangeStr = uiChgUrl.GetProperty("InnerText").ToString();
      string[] words = ChangeStr.Split(' ');
      int ctr = 0;
      for (int i = 0; i < words.Length; i++)
      {
         if (words[i].Contains("http"))
         {
             ctr = i;
             break;
         }
      }
      browser = BrowserWindow.Launch(words[ctr]);
  }

16. There was an example I had considered during one of the previous articles in which I had explained how to re-use and customize code generated during CUIT. I am going to take the same example in which I had selected a search text and found out the articles matching the search criteria. In this case, I am going to write the code for everything though. We are also going to add assertions and decide if the test passes or fails.

I have used SetFocus() method so as to set the focus to the edit box in which the search condition is given. The following code sets focus to the edit box for search and also provides search string. The search string is “Coded UI”

 

UITestControl uiSearch = new UITestControl(browser);
   uiSearch.TechnologyName = "Web";
   uiSearch.SearchProperties.Add("ControlType", "Edit");
   uiSearch.SearchProperties.Add("Id", "ctl00_q");
   uiSearch.SetFocus();
   uiSearch.SetProperty("Text", "Coded UI");

17. Now that the search string is entered, we need to click on the search button:

UITestControl uiButtonSearch = new UITestControl(browser);
uiButtonSearch.TechnologyName = "Web";
uiButtonSearch.SearchProperties.Add("ControlType", "Button");
uiButtonSearch.SearchProperties.Add("Id", "ctl00__btnSearch");
Mouse.Click(uiButtonSearch);

18. The complete method looks as below:

[TestMethod]
public void SearchWebsite()
{
    UITestControl uiSearch = new UITestControl(browser);
    uiSearch.TechnologyName = "Web";
    uiSearch.SearchProperties.Add("ControlType", "Edit");
    uiSearch.SearchProperties.Add("Id", "ctl00_q");
    uiSearch.SetFocus();
    uiSearch.SetProperty("Text", "Coded UI");

    UITestControl uiButtonSearch = new UITestControl(browser);
    uiButtonSearch.TechnologyName = "Web";
    uiButtonSearch.SearchProperties.Add("ControlType", "Button");
    uiButtonSearch.SearchProperties.Add("Id", "ctl00__btnSearch");
    Mouse.Click(uiButtonSearch);

    UITestControl uiSearchResult = new UITestControl(browser);
    uiSearchResult.TechnologyName = "Web";
     uiSearchResult.SearchProperties.Add("ControlType", "Pane");
    uiSearchResult.SearchProperties.Add("Id", "resInfo-0");
        string SearchStr = uiSearchResult.GetProperty("InnerText").ToString();
    string[] words = SearchStr.Split(' ');
    Console.WriteLine(words[1]);
    if (Convert.ToInt16(words[1]) < 150)
    {
         Assert.AreEqual(true, true);
    }
    else
    {
        Assert.AreEqual(true, false);
    }
}

The assert condition can change the way we want to specify when the test passes or fails.

Conclusion:

In this article we discussed how we can hand code Coded UI Test in Visual Studio 2013. We used CUIT Builder to find out information about the objects or spy the objects. We also did not use UIMap in this case.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Gouri is a Trainer and Consultant on Azure DevOps and Azure Development. She has an experience of three decades in software training and consulting. She is a graduate from Pune University and PGDCA from Pune University. Gouri is a Microsoft Most Valuable Professional (MVP)  - Developer Technologies (Azure DevOps), Microsoft Certified Trainer (MCT) and a Microsoft Certified Azure DevOps Engineer Expert. She has conducted over 150 corporate trainings on various Microsoft technologies. She is a speaker with Pune User Group and has conducted sessions on Azure DevOps, SQL Server Business Intelligence and Mobile Application Development. Gouri has written more than 75 articles on Azure DevOps, TFS, SQL Server Business Intelligence and SQL Azure which are published on www.sqlservercurry.com and www.dotnetcurry.com. You can connect with her on LinkedIn.


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Walrick Biviwhale on Monday, December 1, 2014 6:04 AM
In my own Coded UI tests, uiSearch.SetFocus() doesn't seem to work in Firefox or Chrome. Setting the Text property appears to work (the text does change), but in reality it doesn't trigger the underlying javascript events because SetFocus didn't actually set the focus. I found that if I send a Mouse.click on the control instead of calling SetFocus, whilst not entirely ideal, it works.
Comment posted by Sunil AV Kumar on Wednesday, January 7, 2015 6:10 AM
For Partial checkbox there is a property called 'indeterminate' While using test builder it is not listing the property for identification.

Is there any way to add such missing property to test builder?
Comment posted by Shasan on Tuesday, January 27, 2015 1:12 AM
How to test Web browser (IE) on windows Phone 8.1 ?
Please advise!
Comment posted by Punit Bhalla on Wednesday, January 28, 2015 4:45 AM
what to do if test builder is unable to spy the objests on the application how would we test it?
Comment posted by pranav on Friday, March 6, 2015 10:01 PM
Very nice article