Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Tutorials » Automated Code Coverage and Unit Tests

Automated Code Coverage and Unit Tests

A short tutorial that explains how to use a code coverage tool and how it can be integrated with unit tests to allow us to determine how well the unit tests exercise our application/classes. Code examples are written using C#.

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 256
Total page views :  34590
Rating :
 4.25/5
This article has been rated :  4 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ClassUnderTest.zip
 
Become a Sponsor


Related EbooksTop Videos

How well have your tests exercised your code?

Over the course of this tutorial I plan to demonstrate a number of tools and topics that encompass "testing". I'll be looking at code coverage - how much of our code is "exercised" or used. I'll be looking at tools that can help us with code coverage, name NCover and NCoverExplorer. I'll focus on using NUnit for testing and will demonstrate how we can tie it into the code coverage activity. Finally, I'll be looking how we can integrate all of this good stuff into the Visual Studio IDE using TestDriven.NET.

With that in mind, I will go through the following:

  1. The creation of a simple class that does something trivial, in this case a calculator (Visual Studio, C#)
  2. The creation of a simple front-end application that uses the calculator (Visual Studio, C#)
  3. An examination of code coverage using the front-end application (NCover and NCoverExplorer)
  4. An examination of code coverage using unit tests (NUnit)

These four topics will demonstrate two things. Firstly, the benefit of using a code coverage tool to help you learn more about your application and the way that it works. Secondly, how that added benefit of a set of unit tests coupled with a code coverage tool can yield increased levels of confidence in your application's testing strategy. Of course, prior to code coverage tools being automated, the simplest form of code coverage was the debugger: even as recently as 1998 I recall laboriously slaving over the Delphi debugger whilst I was "testing" my application. It was worth the toil, the few additional bugs that came to light meant that the application had years of trouble free use. Now, with code coverage integrated into the IDE, and with unit tests sitting side-by-side with the application source code, the time required to run the tests and perform a code coverage analysis is so short, it can be done with every build.

TestDriven.NET

TestDriven.NET provides an integration layer between a number of testing frameworks, such as NUnit, and the IDE. Before TestDriven.NET, we would write our tests, write some code, build everything and then we would fire up a separate application that would run the tests (e.g. the NUnit front-end). Generally this is/was fine as the benefits of test execution greatly outweighed the use of a secondary application. Whilst the NUnit front-end allows us to choose which tests we want to run (as opposed to running all tests), we still find ourselves leaving the IDE and jumping into another application.

So, in addition to integrating NUnit into the Visual Studio IDE, it also provides integration with NCover and NCoverExplorer.

Code Coverage

For the purposes of this tutorial, I am going to do and explain things in a slightly "out of order" fashion. I know that I have mentioned test-driven development already, and by rights we should be developing our application in that fashion. However, I would like to introduce code coverage first. Luckily the example that I plan to use is so simple, it could almost be tested without the need for test-driven development. The example that I plan to use to demonstrate code coverage is that of a simple calculator - I could have been more original, I apologise for my banality!

The Calculator Class

Implementing a simple calculator isn't rocket science, but since I need you to be at least familiar with the code layout, here's the code that I am using:

namespace ClassUnderTest

{

          public class MyCalculator

          {

                   public int subtract(int a, int b)

                   {

                             return a - b;

                   }

 

                   public int add(int a, int b)

                   {

                             return a + b;

                   }

 

                   public int divide(int a, int b)

                   {

                             return a / b;

                   }

 

                   public int multiply(int a, int b)

                   {

                             return a * b;

                   }

          }

}

Here's a little front-end WinForms application that makes use of [some] the MyCalculator class.

test application

And here's the code behind the WinForms application and the "add" button:

using ClassUnderTest;

 

namespace CalcApp

{

          public partial class FormMain : Form

          {

                       private MyCalculator calc = new MyCalculator();

                       public FormMain()

                       {

                                InitializeComponent();

                       }

                       private void btnAdd_Click(object sender, EventArgs e)

                       {

                                int answer;

                                int a, b;

                                // for demonstration purposes only

                                a = System.Convert.ToInt32(tbA.Text);

                                b = System.Convert.ToInt32(tbB.Text);

                                answer = calc.add(a, b);

                                tbAnswer.Text = answer.ToString();

                       }

          }

}

 

So, having compiled CalcApp, we can submit the .exe to NCover. Before we do that, it's probably useful if I introduce NCover.

What is NCover?

NCover is a command-line tool that scans your application's code and records information about which lines of code were executed. NCover uses the "sequence points" that the compiler generates and stores in the .pdb file (debug information) to determine which lines of code are executed and how frequently. Without getting bogged down in detail, a sequence point is essentially a single program state or a line of code.

NCover's command-line syntax is:

Usage: NCover /c [/a ]

/c Command line to launch profiled application.
/a List of assemblies to profile. i.e. "MyAssembly1;MyAssembly2"
/v Enable verbose logging (show instrumented code)

After NCover has analysed your code, it creates two files: coverage.log and coverage.xml.. The .log file contains the events and messages that NCover creates as it analyses your code base. The .xml file is where it all happens: it contains NCover's analysis of your code base. There is a third file, coverage.xsl. It's an XSL stylesheet that takes coverage.xml as its input, allowing it to be displayed in a neat tabular fashion inside Internet Explorer.

Running CalcApp through NCover

NCover's output:

C:\Program Files\NCover>NCOVER.CONSOLE "...\dev\VS2005\Test\DDG\CalcApp\CalcApp\bin\Debug\CalcApp.exe"
NCover.Console v1.5.4 - Code Coverage Analysis for .NET -
http://ncover.org
Copyright (c) 2004-2005 Peter Waldschmidt

Command: ...\dev\VS2005\Test\DDG\Calc
App\CalcApp\bin\Debug\CalcApp.exe
Command Args:
Working Directory:
Assemblies:
Coverage Xml: Coverage.Xml
Coverage Log: Coverage.Log

Waiting for profiled application to connect...
******************* Program Output *******************
***************** End Program Output *****************

Alternatively, with TestDriven.NET installed, there is the IDE menu integration:

It's important to note that the Coverage menu option is context sensitive. Depending upon "where" you right click, say either on the CalcApp solution or the TestLibrary, NCover will be invoked for the item you right clicked on. We will see this difference emerge later on in this posting when we demonstrate the difference between code coverage for CalcApp vs. code coverage for our NUnit tests.

Now, you may recall that I only implemented the "add" calculation. This is deliberate as I need to use the missing calculations to demonstrate code coverage.

Coverage.xml is too large to reprint here and it's not all that easy to read. Fortunately, NCover's author realised this and created an XSL (stylesheet) that transforms the XML into something a) more readable and b) more useful. The screenshot below presents a snapshot of that output - notice the green bars and red bars, we're clearly in the 'testing' domain now.

From this report, we can easily see that we've only covered 25% of the MyCalculator class. However, and this is a key point, in order to get this far, we had to perform manual testing. We had run the application "through NCover" such that it could watch what was happening. We had to enter the number 38 and 4 and we had to move the mouse and click on the Add button. Whilst this is a better than stepping though code with the debugger, it's not automated therefore it's not repeatable.

NCover's report looks great and it serves a good purpose. NCoverExplorer moves things to the next level, it takes the output from NCover and presents it graphically in a treeview with integrated code viewing:

NCoverExplorer uses colour-coding to highlight the status of code coverage. It is configurable as the screenshot below demonstrates:

Introducing unit tests with NUnit

Without going into too much detail about test-driven development and NUnit, our next step is to prepare a new class that allows us to test the MyCalculator class. In reality, we would have written our tests before writing the MyCalculator class, we're doing things in a slightly different order for the sake of this post.

So, using Visual Studio we simply add a new Class Library to our solution, add a reference to the ClassUnderTest namespace and we're off. The following code demonstrates how we might use the NUnit testing framework to exercise MyCalculator. Whilst not an NUnit requirement, I prefer to name my test methods with the prefix "test", other unit testing frameworks may vary. As you can see, we're simply recreating the manual test that we performed using the desktop application and we're still only testing the "add" method.

using NUnit.Framework;

using ClassUnderTest;

 

namespace TestLibrary

{

          [TestFixture]

          public class MyTests

          {

                   private MyCalculator calc;

 

                   [SetUp]

                   public void SetUp()

                   {

                             calc = new MyCalculator();

                   }

       

                   [Test]

                   public void testAdd()

                   {

                             int n = calc.add(38, 4);

                             Assert.AreEqual(42, n);      

                   }

          }

} 

Inviting NUnit to run these tests, in the absence of TestDriven.NET, would mean leaving the IDE. However, with TestDriven.NET, we can right click on the TestLibrary and run the tests using NUnit. The screenshot below presents the output from the NUnit front-end. It clearly demonstrates that the test for addition succeeded and with that we gain the confidence that "everything's working". However, what it doesn't tell us is the fact that we've missed out testing some 75% of the MyCalculator class. For that, we need to use NCover on our tests.

Here's a screenshot of NCoverExplorer viewing NCover's Coverage.xml after it has analysed the tests:

The key takeaway from this screenshot, and indeed this posting, is the fact that we have automated our test and our code coverage: we can see in a single screenshot how well our tests are exercising our code.

I discovered NCover and NCoverExplorer via a couple of blog posts and was suitably impressed - I am always on the look out for ways of ensuring that my applications are as well tested as they can be. After all, there is nothing worse than a stream of 'phone calls from your users each complaining about a show stopping crash or feature that does not appear to work. With careful use of the tools mentioned above, we can get ensure that our applications are tested and that we have no code that is unused. Code that is unused is often the source of bugs or feature failures. In the past, without tests and without code coverage tools, we had to resort to using a debugger to test all paths through our code - that was a laborious process fraught with repetition and boredom.

My recommendation: install NCover, install NCoverExplorer, install NUnit, install TestDriven.NET.

Resources


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Craig Murphy
Craig Murphy is employed by a leading professional services consulting firm as a Systems Development Engineer. Craig is also an author, developer, speaker, Microsoft Most Valuable Professional and Certified ScrumMaster. He specialises in: XML, web services, XSLT, TDD, .net and XP. He has extensive experience with Borland Delphi spanning some 10 years. Apart from in-house software, Craig has written applications for major oil companies and local councils. He is currently using C# and Visual Studio 2005.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ClassUnderTest.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
Very good by Praveen On April 5, 2006
Very good article
Reply | Email | Delete | Modify | 
Using NCover in ASP.NET Applications by Murali On November 27, 2006

Hi Craig,

Need help to utilize NCover to do the code coverage of ASP.NEt Applications.

Timely help appreciated.

Thanks
Murali

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved