I'm going to be giving a talk to my department next week about unit testing and test-driven development. As part of this, I'm going to show some real-world examples from some code I've written recently, but I'd also like to show some very simple examples that I'll write in the talk.
I've been searching on the web for good examples, but I've been struggling to find any that are particularly applicable to our area of development. Almost all of the software we write is deeply-embedded control systems running on small microcontrollers. There's a lot of C code that is easily applicable to unit testing (I'll be talking about unit testing on the PC rather than on the target itself) as long as you stay clear of the 'bottom' layer: the stuff that talks directly to the microcontroller peripherals. However, most examples I've found tend to be based on string-processing (e.g. the excellent Dive Into Python Roman numerals example) and since we hardly ever use strings this isn't really suitable (about the only library functions our code typically uses are memcpy
, memcmp
and memset
, so something based on strcat
or regular expressions isn't quite right).
So, on to the question: please can anyone offer some good examples of functions that I can use to demonstrate unit testing in a live session? A good answer in my (subject to change) opinion would probably be:
- A function that is simple enough that anyone (even those who only write code occasionally) can understand;
- A function that doesn't appear pointless (i.e. working out the parity or CRC is probably better than a function that multiplies two numbers together and adds a random constant);
- A function that is short enough to write in front of a room of people (I may take advantage of Vim's many clipboards to reduce errors...);
- A function that takes numbers, arrays, pointers or structures as parameters and returns something similar, rather than handling strings;
- A function that has a simple error (e.g.
>
rather than>=
) that's easy to put in that would still work in most cases but would break with some particular edge case: easy to identify and fix with a unit test.
Any thoughts?
Although it's probably not relevant, the tests themselves will probably be written in C++ using the Google Test Framework: all our headers already have the #ifdef __cplusplus extern "C" {
wrapper around them; this has worked well with the tests I've done so far.