Monday 14 October 2013

Coded UI Testing in Visual Studio 2012

Coded UI Test are the tests which helps in testing if the application works well from the user point of view i.e. it helps in testing the user interface of the application. Basically these are the automated tests which helps in performing the functional testing of the UI, it is very helpful in testing the logics if the there are some logic written like some kind of business logic and the validation logic (Which do exist on User Interface for most of the applications)

Coded UI test provides the flexibility to test if the controls on user interface contain the correct values and also helps in testing condition based actions which output different results in different conditions. One can check the behaviour in of the application or the UI in different browsers as most of the time UI faces problem in different browsers.

For creating down a Code UI Test, just simply run your application and perform test manually while the Coded UI Test Builder runs in the background. Once the test is performed manually in the UI, you will see that the Coded UI Test Builder has recorded your actions, and you can generate script for the same. Once can now edit this test and also can change the sequence of the actions performed in the test, so in this way it provides you with the lot of flexibility.

So how do it works??? It basically generates a UI Map which represents the window and various other controls which are present on the UI. Now while you was performing some manual actions while doing manual testing it will record your actions and generates some assertions corresponding to them, finally you can generate scripts for these recording(s). Now if you will look into the scripts, you will see that the UI controls has been accessed via UI map and then the various events have been performed or executed or triggered upon them just like if you have clicked the button while doing manual testing, recorded that and generate the script for the automation test then you will see in the script that the with the help of Coded UI button has been accessed and the Click event of that button is triggered in the script.

CUITe is one of the Coded UI Test Framework which is developed on the top Microsoft Visual Studio Test Engine; it helps in reducing the complexity and coding effort and helps in increasing maintainability.

Let’s see how to create Coded UI Test cases:

So here I will be creating a very simple application in which I will but two text boxes and a button, and finally we will create a Coded UI test case for verifying if it is working fine or not.

So if you will look here I have added a simple Web Site in the solution, add on the “Default.aspx”, I have added two textboxes and a button.




Now I am going to write some code, here I will not be providing you with the Login Solution I just want to demonstrate the use of Coded UI, so what I am going to do is write down some code to take the values enter by user, handle it on login click and display message to the user in a label.


Now this is the sample page for which we can create Coded UI test cases. Let’s see if it running or not.


So now create a Coded UI Test Project in the Solution, Remember that you are using Visual Studio Premium Edition or the Ultimate Edition as it is available only in these two Editions by default.


As soon as you will add a Coded UI test project, a Coded UI Test will automatically will be added and you will be popped up with a dialog box shown below:


Select option “Record action, Edit UI map or add assertions”. So every time you will add a new test case of type Coded UI you will popped up with this dialog box. So you can create a new test case with already existing recording or you can create with the help of new recording.

As soon as you will click ok in the dialog box your Visual Studio will be minimized with a tray which appears on the right bottom of your screen.


So with the help of this tray you can perform recording of the action for which you want to generate test cases. So from here you can start recording the test, can add assertions, can edit the actions and finally can generate the code for the test case both in VB as well as in C#.

Start Recording

Start Recording means all the actions which will be performed will be recorded, so if you want that in your test case the application should be launched (Which you obviously want) then that should also be captured in the recording, So Start recording and open the browser, type in your application address in address bar and start performing the test case steps in the application or start using the application. In my case what I have done is I have started the application without debugging, and as soon as the window gets launched I started the recording.


Now I entered the values in the text boxes as I wanted i.e. “abhishek” in both the text boxes and clicked on Login and a message appears saying that the operation is successful, after this I paused the recording and clicked on Generate Code. On doing so following window appears and I names by first method as “LoginSuccess”.


Add Assertions
Assertions, you must be familiar with this term if you have ever written down any test case, so adding assertions in Coded UI is the process by which you can actually check the properties and value of any UI control. So for this just choose Add Assertions in the tray, then choose the control on which you want to assert, then select the assertion property, select the comparison type and the expected value along with the error message.

So now what I have done is dragged the Add Assertion target icon over the success message in my Web Form, and as soon as I done this following window appears in which I selected Display Text property of my label and added an assertion over it saying that this text should be equal to “Success!”



Now again after doing so again I clicked upon on the Generate Code and generated a new method for this assertion as shown below:


Running Test Cases

Now if you will see the Code file i.e. CodedUITest1.cs, you will see that there are two methods which are generated automatically.


Now we are ready with the test case, now it’s time to test it. So before starting close the test case builder and previously opened instance of the browser, Rebuild your code, and again start the application without debugging.



Now after launching your application just go to “Test Explorer” and execute that test case, now you will see on the browser instance, the values getting entered automatically in the text boxes, button click and then finally your will see the result that the test case passed.


So here you can make multiple assertions as required on one or various controls present on your web page. Also one can make negative assertions as per the requirements. This is a very basic example although one can write or record more complex test cases as per the requirement. For Downloading the sample Application (follow: SampleApplication) which I created while writing this article, you can have a look into it if it helps.

I mentioned write Coded UI test cases in above paragraph, yes you can write down or modify the code if you are good if you don’t like doing the recording much.

Tuesday 8 October 2013

Create OData Web Services and Use Filter Expressions

OData (Open Data Protocol) lets you expose your resources and let the clients directly do the queries over it. Earlier when we used to use SOAP, you expose some methods, which performs some operations over the data returns back you the results, and if any client needs some specific data, then we used to changes our services by exposing down a new method which returns the needed output. But with OData also known as Resource Oriented architecture, we can just expose the resources or the data and let the client make the queries according to the requirement.

Here in this article of mine I will show you how to create a simple OData Service and let the client make queries just like SQL queries over it to retrieve the required data. Queries can be made by just specifying the filter expressions in the URL only.


So to start with I have created a WCF Service Application.


After creating we need to create a Data Service, which is done by just the following, some simple steps: Right click on the WCF application, and Add WCF Data Service as shown in the screenshot below.


As soon as it is done, you will see the generated service file:

    public class SampleWCFDataService : DataService< /* TODO: put your data source class name here */ >
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        }
    }

I have highlighted in yellow, to get the service ready to be used we need to specify the Data Source Class, this can be achieved by simply providing Entity Framework Model for a particular database. So what this Data Source class should support is IQueryable properties over the exposed entities. Entity Framework model exposes all your entities as IQueryable properties. It allows directly exposing your tables and letting the client make queries over it by using Filter Expressions.

But for the sake of keeping it simple I am not creating Entity Framework model and will be creating a Data context class which have IQueryable properties.

So let’s look into how to create DataContext Class, before that we need to create some entities (Data Service Entities) which will be exposed as IQueryable entities via this DataContext class, here I will be creating a single entity User:

    [DataServiceKey("Id")]
    [DataServiceEntity]
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

Attribute has been added specifying the User class as Data Service Entity. Now we will create a context class:

    public class SampleContext
    {
        #region Static Constructor

        /// <summary>
        /// In this static constructor i am creating some data which will be filled into users list, the purpose of creating static constructor is that it will be executed once
        /// on the creating of very first object and fills in some data into the users list which we can use to run through the demo.
        /// </summary>
        static SampleContext()
        {
            users = new List<User>();

            User user1 = new User();
            user1.Id = 1;
            user1.Name = "Abhishek1";
            user1.Age = 20;

            User user2 = new User();
            user2.Id = 2;
            user2.Name = "Abhishek2";
            user2.Age = 30;

            User user3 = new User();
            user3.Id = 3;
            user3.Name = "Abhishek3";
            user3.Age = 40;

            users.Add(user1);
            users.Add(user2);
            users.Add(user3);
        }

        #endregion

        #region Private Members

        static IList<User> users;

        #endregion

        #region Public Methods

        public IQueryable<User> Users
        {
            get
            {
                return users.AsQueryable();
            }
        }

        #endregion
    }

Now you can see that I have provided the Data Source for the Data Service we created earlier to this context class:


With this we are ready to use this service:


So above you can see that the Data Service is working, and the format in which it is displayed above is the Atom pub format. By default it doesn’t exposes the Data Context we created and set in the Data source in the service. For achieving so what we have to do is in the service code just uncomment the code highlighted in yellow, what this code do is, it defines the Entity access rule for the entities (Which all entities are needed to be exposed) so what we doing is we are exposing the entity Users below and are setting the Access level to Read, so we are only allowing Read operations.

    public class SampleWCFDataService : DataService<SampleContext>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.SetEntitySetAccessRule("Users", EntitySetRights.AllRead);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    }

Now if you will access the Service again you will see something like below:


So here we get a new collection users, which we can use in the URL (Same as REST format) to get the users collection.


So here we are getting the Users Collection in the Atom PUB format shown above. So what’s the use of this is we can make a request to this URL (http://localhost/SampleWCFDataService.svc/Users) from a Web Page or a JavaScript file (Data can be returned in JSON format) can use the output i.e. Users list in the Web Page.

If we understand the format above we can see that it already provides the things to determine how we can query down the Data Source or can user filter expressions in it. Just for the sake of understanding I am formatting the output above in XML Format.

<?xml version="1.0" encoding="utf-8"?>
<feed xml:base="http://localhost:51937/SampleWCFDataService.svc/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <id>http://localhost:51937/SampleWCFDataService.svc/Users</id>
  <title type="text">Users</title>
  <updated>2013-10-08T14:44:06Z</updated>
  <link rel="self" title="Users" href="Users" />
  <entry>
    <id>http://localhost:51937/SampleWCFDataService.svc/Users(1)</id>
    <category term="SampleService.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <link rel="edit" title="User" href="Users(1)" />
    <title />
    <updated>2013-10-08T14:44:06Z</updated>
    <author>
      <name />
    </author>
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">1</d:Id>
        <d:Name>Abhishek1</d:Name>
        <d:Age m:type="Edm.Int32">20</d:Age>
      </m:properties>
    </content>
  </entry>
  <entry>
    <id>http://localhost:51937/SampleWCFDataService.svc/Users(2)</id>
    <category term="SampleService.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <link rel="edit" title="User" href="Users(2)" />
    <title />
    <updated>2013-10-08T14:44:06Z</updated>
    <author>
      <name />
    </author>
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">2</d:Id>
        <d:Name>Abhishek2</d:Name>
        <d:Age m:type="Edm.Int32">30</d:Age>
      </m:properties>
    </content>
  </entry>
  <entry>
    <id>http://localhost:51937/SampleWCFDataService.svc/Users(3)</id>
    <category term="SampleService.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <link rel="edit" title="User" href="Users(3)" />
    <title />
    <updated>2013-10-08T14:44:06Z</updated>
    <author>
      <name />
    </author>
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">3</d:Id>
        <d:Name>Abhishek3</d:Name>
        <d:Age m:type="Edm.Int32">40</d:Age>
      </m:properties>
    </content>
  </entry>
</feed>

So if we type in the above highlighted command directly into the Address bar we will get something like below which is the very first user in the list:

<?xml version="1.0" encoding="utf-8"?>
<entry xml:base="http://localhost:51937/SampleWCFDataService.svc/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <id>http://localhost:51937/SampleWCFDataService.svc/Users(1)</id>
  <category term="SampleService.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <link rel="edit" title="User" href="Users(1)" />
  <title />
  <updated>2013-10-08T14:53:39Z</updated>
  <author>
    <name />
  </author>
  <content type="application/xml">
    <m:properties>
      <d:Id m:type="Edm.Int32">1</d:Id>
      <d:Name>Abhishek1</d:Name>
      <d:Age m:type="Edm.Int32">20</d:Age>
    </m:properties>
  </content>
</entry>

This is how the service works and we can actually directly consume the data into the Web Page where we need to. Now we will look into how to use filter expression directly while accessing the Data Service and retrieve the results. There are lot filter expressions available:

  • And
  • OR
  • Less Than(equal to)
  • Greater Than(equal to)
  • Not Equal
  • Ends with
  • Starts With
  • Length
  • Index Of
  • Replace
  • And many more…

How to actually use them, so if I consider the above scenario in which we are getting the Users collection, now if I want to get all the users which are actually having age greater than 22, then we can simply make a filter query(http://localhost/SampleWCFDataService.svc/Users?$filter=Age gt 22) and get the results.


<?xml version="1.0" encoding="utf-8"?>
<feed xml:base="http://localhost:51937/SampleWCFDataService.svc/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <id>http://localhost:51937/SampleWCFDataService.svc/Users</id>
  <title type="text">Users</title>
  <updated>2013-10-08T15:13:42Z</updated>
  <link rel="self" title="Users" href="Users" />
  <entry>
    <id>http://localhost:51937/SampleWCFDataService.svc/Users(2)</id>
    <category term="SampleService.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <link rel="edit" title="User" href="Users(2)" />
    <title />
    <updated>2013-10-08T15:13:42Z</updated>
    <author>
      <name />
    </author>
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">2</d:Id>
        <d:Name>Abhishek2</d:Name>
        <d:Age m:type="Edm.Int32">30</d:Age>
      </m:properties>
    </content>
  </entry>
  <entry>
    <id>http://localhost:51937/SampleWCFDataService.svc/Users(3)</id>
    <category term="SampleService.User" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <link rel="edit" title="User" href="Users(3)" />
    <title />
    <updated>2013-10-08T15:13:42Z</updated>
    <author>
      <name />
    </author>
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">3</d:Id>
        <d:Name>Abhishek3</d:Name>
        <d:Age m:type="Edm.Int32">40</d:Age>
      </m:properties>
    </content>
  </entry>
</feed>

So as it should be it is returning only two users, now let’s make it something like greater than 22 and less than 35(http://localhost/SampleWCFDataService.svc/Users?$filter=Age gt 22 and Age lt 35) which should return only one result. Now here we have seen the use of both Greater than, less than and the “and” expressions.


Similarly you can use the other available filter expressions. You can also download the sample application(From Here: Download) to see the working.