In-Depth

Write Tests Before You Code

Use the Test-Driven Development methodology in Visual Studio Team System to write tests and improve the quality of your code.

Welcome to Visual Studio Magazine's new online column on Microsoft Visual Studio 2005 Team System (VSTS). Twice a month I will introduce you to concepts in VSTS, for beginners and professionals alike. If you have a question about an aspect of VSTS that you would like to suggest I address in a future column, please send it to [email protected].

In this debut column, I will demonstrate how to use Team Edition for Software Testers for writing code in accordance with the Test-Driven Development (TDD) methodology. Oddly enough, many developers still do not write unit tests for their code, much less write tests before they write code! Using the TDD process, you write tests before you write code. Two of the most compelling reasons for this approach are (1) all code you write will be testable, and (2) you will not write any unnecessary code. At the very least, even if you decide not to adopt TDD, you will see the value of the unit-testing features in Team System and incorporate them in your process to build better applications.

There are advantages and disadvantages to using TDD. For agile methodologies, incorporating TDD offers a huge benefit because you do not conduct significant upfront design in agile development. TDD does not allow you to create class diagrams and perform optimization up front. However, TDD does make it extremely easy to refactor code you've written. TDD generally prevents you from "gold plating" an application — that is, adding code that is unnecessary and often unused — and it is incredibly simple to add to an application without breaking the whole thing!

Team System implements a generic unit-testing framework that can be adapted to virtually any situation. Team System can be used for TDD, but not in the purest sense of the word. In the TDD process you create a unit test that will break ("red"), fix the method being tested so the test passes ("green"), and refactor — then start the cycle over again. Because you create the test before the method, the test is guaranteed to fail. Typically when performing refactoring, you have a somewhat larger body of code to work from. The good news is that for the purposes of regression testing, almost all of your tests are written already!

Using VSTS you can generate method stubs from your unit test, but you need to create the class that is going to house the method stub first. This is really the only limitation when using VSTS's unit testing from a purist's perspective.

To create your first test, create a new VS Console application. Add a new public class called "Calculate." Select Test > New Test from the main menu, and select Unit Test from the Add New Test dialog. Name the test "CalcTests" (this is not actually the name of the test but is used as the name of the class).

One best practice I suggest is to append "Test" to the name of the method you are going to test — if you write more than one test per method, which is likely, either describe the test or append numbers and enter a description. For example, you may have "AddTestPositiveNumbers" or "AddTest1" with a description. (To enter the description select Test > Windows > Test Manager or Test View and select the test, then add a description in the Properties window.)

Create a new test project (your tests should in generally always be separate from your application code base) and call it "AppTests." Change the name of the test method to "AddTest." Next, add a reference to the ConsoleApplication1 project to the AppTests project and import it in the CalcTests module.

Next, add the following to the test method (entire method is shown for reference):

        [TestMethod]
        public void AddTest()
        {
            int x = 5;
            int y = 10;
            int result = 0;
            int expected = 15;

            Calculate c = new Calculate();

            result = c.Add(x, y);

            Assert.AreEqual(expected, result,
 "Values are not equal");
        }

When you enter result = c.Add(x, y); "Add" will be underlined and you'll be given the option to generate a method stub. When you select this option, the following stub is generated in the Calculate class:

        public int Add(int x, int y)
        {
            throw new Exception("The method or operation is "
            + "not implemented.");
        }

The Assert method is a class with a collection of static methods that allows you to evaluate one or more values that you use to determine if a test passes. Run the test by selecting Test > Window > Test Manager or Test Viewer, check the AddTest entry, and select the Run Checked Tests button. The test will, of course, fail. Change the Add method to read:

        public int Add(int x, int y)
        {
            return x + y;
        }

Compile the application and re-run the test — this time it passes. You're on your way to developing code with TDD.

VSTS allows you to perform many more advanced operations, such as extending the testing framework, creating data-driven tests (test data supplied from a database), checking code coverage and providing other tools to help improve the quality of your code. I will explore these features and more in future columns.

About the Author

Jeff Levinson is the Application Lifecycle Management practice lead for Northwest Cadence specializing in process and methodology. He is the co-author of "Pro Visual Studio Team System with Database Professionals" (Apress 2007), the author of "Building Client/Server Applications with VB.NET" (Apress 2003) and has written numerous articles. He is an MCAD, MCSD, MCDBA, MCT and is a Team System MVP. He has a Masters in Software Engineering from Carnegie Mellon University and is a former Solutions Design and Integration Architect for The Boeing Company. You can reach him at [email protected].

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube