August 2005 Archives

Test Driven Development

| | Comments (0)

I have been using test driven development for my C++ projects for some time now, a development process which has improved the quality of my code considerably. The process is relatively straight forward, the only hurdle to get over is understanding that the tests should drive the structure of your code, not the other way round.

A simple example of the steps you go through follow, here I will create a simple function to add two numbers:

1. The first stage is to write a small test, in this case we can check that 2 + 2 = 4

ASSERT(AddTwoNumbers(2, 2) == 4);

2. Now we have our test we can write a function to implement just enough to pass the test:

int AddTwoNumbers(First, Second)
{
return 4;
}

3. You can see here we have taken a pretty extreme example but it shows the principle that you take very small steps forward to make sure your tests and code are thorough.

4. Running our test will now pass but we know we need to do a bit more, so now we can add a new test to break the code:

ASSERT(AddTwoNumbers(1,2) == 3)

5. Now our test fails and we need to add some more code to fix the test:

int AddTwoNumbers(First, Second)
{
return First + Second;
}

Ultimately we will end up with a suite of tests which cover the code extensively however this isn’t the final stage. There may be some duplication in the code so we should refactor it to remove any repeated sections while continuing to run the tests to make sure nothing gets broken. The tests provide a check on the quality and should be run with every build and check-in to make sure nothing gets broken.

So how does this relate to writing a printer driver, the main problem I face with the driver is I haven’t written one before so everything is new. There is documentation as part of the DDK but it is pretty poor and if you visit the DDK newsgroups a substantial number of replies to new driver writers just point people to the samples in the DDK. This is fine except the samples are standard driver code, they obviously haven’t been in any way to help people understand what is required of the various functions.

My solution to this problem has been to write tests which exercise the sample driver, as I implement each function I can load up the DLL’s from the sample plotter driver and create tests for each exported function which let me explore the way it works. Once I have a complete and rounded set of tests for the sample I can then run those tests against my own code and start fixing the failures and adjusting the tests which should be different.

About this Archive

This page is an archive of entries from August 2005 listed from newest to oldest.

July 2005 is the previous archive.

January 2006 is the next archive.

Find recent content on the main index or look in the archives to find all content.