Showing posts with label VSTS. Show all posts
Showing posts with label VSTS. Show all posts

Tuesday, April 17, 2012

Unit testing using LINQ in Visual Studio Team System

Definition for Unit Testing


In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure. (Source: en.wikipedia.org/wiki/Unit_testing).

How to use LINQ in unit testing


OK, For a unit testing we require test data. In VSTS (Visual Studio Team System), test data can be acquired using following methods.

  1. Using a Database
  2. Using XML and LINQ

I am going to do a walk through on second part i.e. Using XML and LINQ. XML files are quite handy and always liked by developers due to its readability, flexibility etc. But mean time it comes with an additional over head of traversing XML file and use the data. Normally we need to use XML parser to read XML files, then traverse thorough elements, find it and then use it. Lot of additional coding, ha...

But LINQ made this step very easy. Let's see how it works. I will explain through some sample coding.

Before talking about that, if  you need to know how to create unit test class in your application, please refer MSDN http://msdn.microsoft.com/en-us/library/ms182532.aspx.

OK, Let back to our topic. I will explain in three steps.

Step 1: First use following namespace in your unit test class file.
using System.Linq;
using System.Xml;
using System.Xml.Linq;

Step 2:
Now we need to load the element from file. We can use XElement.Load(path) to load the XML data from file.Code sample which will fetch the complete XML data to this variable
          XElement testDataFromFile = XElement.Load(Path);

Step 3:
Below line of code will extract contents of specific elements to the varible. Here LINQ is so flexible and easy that you can query based on element name and you will get the data. So easy, is it? I love this.

     var RSAContracts = from r in testDataFromFile.Elements("RSAContract")
                              select r;
     foreach (var contract in RSAContracts)
     {
         if (contract.Element("TestType").Value == "SuccessPath")
          {
           //Extract the data and fill it to object for testing. ………..
           }
     }

Advantage of using XML files will be

  1. You can extend the test cases any point of time.
  2. Maintainability will be easy. If you are using Database, then you need to create tables, accessing them etc.


Happy programming!!!!