Wednesday, May 15, 2013

Test Driven Development - Part III - Microsoft Testing Tools

Microsoft has also developed their own testing tools. Since VS2005, It has been integrated with the IDE. One of the main advantage of using Microsoft testing tool is the debugging feature with it. But it is not a standalone application. So you need to open the project whenever you want to run the tests.

We can start by opening the same project we did in the previous example.
Add new project to the solution by selecting File => Add => New Project => Visual C# => Test => Unit Test Project.(In VS2010 we had an option to create unit test project by right clicking on the method and selecting 'Create Unit Tests...'  from the popup menu. In VS2012 that feature has been dropped.)

Enter the Name "TddwithNunit.Tests2" and press OK button
The Project will be added to the solution. The project will be referenced to "Microsoft.VisualStudio.QualityTools.UnitTestFramework " and the project will have the following code.

 using System;  
 using Microsoft.VisualStudio.TestTools.UnitTesting;  
 namespace TddwithNunit.Tests2  
 {  
   [TestClass]  
   public class UnitTest1  
   {  
     [TestMethod]  
     public void TestMethod1()  
     {  
     }  
   }  
 }  

Unlike Nunit, Microsoft uses [TestClass] and [TestMethod] attributes for Class and Methods respectively. Add reference to the TddwithNunit project. Rename the class file to "FileUploadTests" and modify the code as below.

 using System;  
 using Microsoft.VisualStudio.TestTools.UnitTesting;  
 namespace TddwithNunit.Tests2  
 {  
   [TestClass]  
   public class FileUploadTests  
   {  
     [TestMethod]  
     public void ValidateFileName_FilnameShorterthan6letters_ReturnsFalse()  
     {  
       //Assign  
       fileupload file = new fileupload();  
       //Act  
       var result = file.ValidateFileName("abc.txt");  
       //Assert  
       Assert.IsFalse(result, "Shorter Filenames are returning true");  
     }  
   }  
 }  


Now build the solution.

Select => Test =>Run =>All Tests . The result of the test will be displayed in Test Explorer inside the IDE as below.


The test has been failed. This logic has not been implemented into the ValidateFilename method. We have to refactor the code as below

 public class fileupload  
   {  
     public bool ValidateFileName(string filename)  
     {  
       bool returnvalue = false;  
       if (filename != string.Empty)  
       {  
         var filepart1 = filename.Split('.').First();  
         if (filepart1.Length >= 6)  
           returnvalue = true;  
       }  
       return returnvalue;  
     }  
   }  
 }  

And run the Test again from the Test Explorer => Run All


The test has been succeeded this time.

No comments:

Post a Comment