Write Unit Tests
Make sure changes you make to your apps don't cause unwanted side effects.
by Nick Smith
December 2002 Issue
Technology Toolbox: VB.NET, C#
You might be familiar with the all-too-common experience of making a change to an application, testing it, and releasing it, only to discover that the change you made broke something elsewhere in the app. Unless you test your application fully, you can't be sure changes you make won't affect another part of the system. In some organizations, quality assurance (QA) departments are responsible for catching knock-on effects. However, the release-to-QA, fix, release-back-to-QA cycle can take a considerable amount of time. Besides, not everyone has a QA department. You need a methodology for making changes that minimizes the risk of unforeseen side effects. Enter unit testing.
The premise for unit testing is that you write discrete tests to test your application's functionality. You run your unit tests after you've made any changes to the system. If all tests pass, you can be confident the application still executes as you intended. You still have no guarantee it will, because the change might cause a problem a unit test doesn't cover. And unit tests can't replace system tests QA departments write and perform. But unit testing is a useful safeguard.
You write tests for each method belonging to a class that exhibits some type of measurable effect. The scope of method types you'll test is up to you. I usually write tests for each public/protected method and for any private methods I think play an important role in the class's functionality. You can group unit tests together to form test suites, which a unit-testing tool can then execute automatically.
My introduction to unit testing came when I began working on an Extreme Programming (XP) project (see the sidebar, "Take Programming to an Extreme"). I'd been writing tests for my code for several years, but most had been full component tests. Each test that I'd written had performed some complex processing and returned a measurable result. With unit tests, you write fine-grained tests for each piece of functionality. For example, if you have a component consisting of one public class and 10 private classes, you write unit tests for all 11 classes, not only the one public class.
You need to use an automated unit-testing tool to write effective unit tests. A huge range of tools isn't available for .NET at the moment. For the purpose of this article, you'll use dotUnit—an open source port of JUnit, a popular Java unit-testing tool you can download (see Resources). (If you search for "unit test" at www.opensource.net, you'll see that unit-testing tools are available for most languages, including ASP.NET). This article's example code is in C# (you can download it and a VB.NET version here).
Back to top
|