An Overview of Unit Testing using Visual Studio Team System

Posted by: Subodh Sohoni , on 3/17/2008, in Category VSTS & TFS (Azure DevOps)
Views: 71955
Abstract: Unit testing is to test the custom code unit immediately after it is created or even as a part of its creation process. The reason to do the unit testing is to catch the errors in the code at an early stage. This improves the overall quality of the application being created. In this article, we will explore Unit Testing using VSTS
An Overview of Unit Testing using Visual Studio Team System
 
Unit testing is to test the custom code unit immediately after it is created or even as a part of its creation process. The reason to do the unit testing is to catch the errors in the code at an early stage. In a complex application, earlier the errors and bugs are detected and removed, lesser are the efforts required to debug the entire application in more advanced stages. This improves the overall quality of the application being created. A custom code unit usually is a class in the application code. Test is a method in a specially adorned class which is executed by the test environment like VSTS.
Unit testing involves providing input to the method of the unit for which output is known. The results obtained by executing the methods are compared against known output values. If they match with each other then the test passes or else it fails which entails corrections in the applications custom code.
In Visual Studio Team System, during unit testing, we write a test class which has test methods. Test methods create instance of the class in the application code and call its method. Parameters to these methods are the values for which output is known. Unit Test in VSTS is created in the following two ways:
1.       Creation using wizard
2.       Authoring the code of the test
Creating the unit test through wizard provides many advantages. Some of them are listed below:
 Unit Test
In VSTS unit testing every test starts in the Pass status. The test environment is notified of the test results through Asserts. Asserts denote ‘truth or what is believed to be truth’. In VSTS Assert class which is in ‘Microsoft.VisualStudio.TestTools.UnitTesting’ namespace has many methods which are used to compare results and known output values.
Assert and its derived classes – stringAssert and CollectionAssert have following methods:
Assert
Behavior of the test classes and test methods is governed by some attributes. These attributes are as follows:

Attribute
Description
TestClass()
This attribute denotes a test fixture. This is to be given to the class which contains test methods
TestMethod()
This attribute denotes a test case.
AssemblyInitialize()
Methods with this attribute are executed before executing the first TestMethod() in the first TestClass() selected for execution.
ClassInitialize()
Methods with this attribute are called before the execution of the first test.
TestInitialize()
Methods with this attribute are called before the execution of each TestMethod().
TestCleanup()
Methods with this attribute are called after the execution of each TestMethod().
ClassCleanup()
Methods with this attribute are called after the execution of ALL tests.
AssemblyCleanup()
Methods with this attribute are executed after executing the last TestMethod() in the first TestClass() selected for execution.
Description()
Provide a description for a given TestMethod().
Ignore()
Ignore a TestMethod() or a TestClass() for any reason.
ExpectedException()
When testing for a specific exception, an exception specified with this attribute will not fail a test if it is thrown from the implementation code.

 An example of unit test using these attributes and assert is as follows:
[TestMethod()]
public void DebitTest()
{
    string customerName = "Mr. Bryan Walton";
    double balance = 11.99;
    BankAccount target = new BankAccount(customerName, balance);
    double amount = 11.22;
    target.Debit(amount);
    Assert.AreEqual((System.Convert.ToDouble(0.77)), target.Balance, 0.05); // 0.05 is tolerance for floating-point comparison
}
An important property on test classes is the TestContext property. This property contains information including the name of the unit test that is currently running, the deployment directory, the names of log files, and for data-driven testing, the database to which you are connected. The TestContext property returns a TestContext instance.
Many a times, we are in a situation to test a method for multiple input values, each having a different output value. We can code it in different ways. One is to put the test logic in the loop and get the output values which are then compared with the known output values. VSTS Testing framework provides us easy way to create a data driven unit test. In this data driven unit test, we create a test database containing input and related output values as records in a table. Without writing the logic of the loop, test framework takes care of picking up records from this test database one by one and executing the test with the data from the currently picked up record.
We can use the DataSource attribute to hardcode the database connection string and the table name. It is done through a wizard started with setting of the Connection string property of the test. We need to also set the Data Table property. The datasource attribute gets automatically populated by this wizard. Drawback of this method of providing the datasource is the hardcoded path of the database. If we need to change the path in future, we will need to recompile the application.
To avoid such tight coupling of the database to the code, we can provide the connection string to the datasource through a configuration file namely App.config. A sample of the App.config with settings to provide datasource is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <configSections>
    <section name="microsoft.visualstudio.testtools"         type="Microsoft.VisualStudio.TestTools.
UnitTesting.TestConfigurationSection,
Microsoft.VisualStudio.QualityTools.UnitTestFramework,
Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
 </configSections> 
 <connectionStrings>
    <add name="dataDrivenTesting"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\VSTSDemo\VSTSDemo.Test\TestDB.mdb" providerName="System.Data.OleDb"/>
 </connectionStrings>
 <microsoft.visualstudio.testtools>
    <dataSources>
      <add name="dataDrivenTestingDS" connectionString="dataDrivenTesting"
        dataTableName="Users" dataAccessMethod="Sequential"/>
    </dataSources>
 </microsoft.visualstudio.testtools>
</configuration>
Benefits of Unit Testing are:
•        They provide preemptive actions on bugs.
•        They create first level of documentation
•        They are easily automated
•        Ideal for testing implementation across different machines.
•        They provide model for configuration, implementation, and execution of actual application code.
Conclusion:
With Visual Studio Team System, Microsoft has made unit tests one of the first class citizens in its development cycle. In VSTS, unit tests can be generated from the code which is created by the programmer or it can be created first, even before the code which is to be tested is created. This methodology is called “Test Driven Development” or “Test First Development”. Unit tests can increase its use by incorporating data to be tested in it. I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
 
 

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 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 eBook 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 .NET Standard and the upcoming C# 8.0 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
Subodh is a consultant and corporate trainer. He has overall 28+ years of experience. His specialization is Application Lifecycle Management and Team Foundation Server. He is Microsoft MVP – VS ALM, MCSD – ALM and MCT. He has conducted more than 300 corporate trainings and consulting assignments. He is also a Professional SCRUM Master. He guides teams to become Agile and implement SCRUM. Subodh is authorized by Microsoft to do ALM Assessments on behalf of Microsoft. Follow him on twitter @subodhsohoni


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Deff Jeromy on Sunday, March 23, 2008 10:52 AM
A very nice article subod..keep up the great work you guys are doing..the content of the site is 5 stars.
Comment posted by Raghavan on Thursday, May 8, 2008 12:38 AM
Nice Article.Gives clear picture on the basis of test edition.
Comment posted by Sajjad on Thursday, August 7, 2008 3:57 AM
Hi!
Plz tell me how we can test function that return nothing, means void.
and one thing is that can we test form events using VSTS?
plz reply me at my email address?
Comment posted by sinu xavier on Monday, October 20, 2008 6:27 AM
your article is very useful for me
thank you
Comment posted by sujith on Wednesday, October 22, 2008 7:09 AM
superb
Comment posted by abc on Tuesday, December 10, 2013 5:44 AM
good artical

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook