Tuesday, December 2, 2008

Unit Testing

A Google search for "test-driven development" will lead you to a lot of information on the idea behind creating test scenarios to improve quality in software. These test scenarios are also called "unit tests" because they are designed to test one single software feature. In addition to achieving higher quality in your application, test-driven development is a critical part of keeping a product healthy and maintainable. But I'm getting ahead of myself. What is a unit test and why should you care? Let's say you are writing a method that calculates the average of three numbers:
public double CalculateAverage(int a, int b, int, c)
{
  int sum = a + b + c;
  return sum / 3;
}
One way to ensure that the code you wrote is working effectively is to write some code that calls your method.
[TestMethod]
public void CalculateAverageTest()
{
 double actualAverage = CalculateAverage(2, 3, 4);
 double expectedAverage = (2 + 3 + 4) / 3;

 Assert.AreEqual(expectedAverage, actualAverage);
}
  • "[TestMethod]" tells Visual Studio that this method is a unit test.
  • "expectedAverage" contains the value that I manually calculate without using my CalculateAverage method.
  • "Assert" is a class that contains methods that verify any kind of statement that you want to make -- in this case, that the expected value matches the value computed by my CalculateAverage method.
Look for the "TestSuite" folder in the solution to find all of the projects that contain unit tests. The "ClientControllerTest.cs" file in the ControllersTest_CSharp project contains a lot of good tests for you to look over. Click on the "Test" menu in Visual Studio, then "Windows", and then "Test View" to view the window that lets you run tests. Right-click any of these tests and click "Run" or "Debug". Sometimes writing unit tests can be a bit tricky; especially when your code involves selecting and updating data in the database, because you are relying on data that might be changed by someone else, for instance. The answer to this is: do the best that you can given the importance and complexity of the code you are testing. In other words, do not spend hours trying to properly and exhaustively test code that is doing something very simple. However, if you are writing a critical or highly-used piece of the system, writing thorough unit tests might take days and is probably well worth it. One of the big benefits of this style of development is that it gives you a lot of confidence whenever you need to modify old code. In the example code from this post, what if I come back six months later and change how averages are computed? How can I be sure that my changes won't break other parts of the application? As long as I have unit tests already written, I can simply run those tests and work on my changes until I get a "Passed" result.

1 comment:

PC said...

I am finding these Unit Tests pretty useful...!! Thanks Colin.