TDD Example - writing software spec and test cases

     Before starting TDD, I need software spec and test cases. My goal is demonstrating software development process with a simple example:fizzbuzz problem. 

    Here is software spec for fizzbuzz problem:

1. if given number is divided up by 3, print fizz. 

2. if given number is divided up by 5, print buzz. 

3. if given number is divided up by both 3 and 5, print fizz buzz. 

4. otherwise, print given number.

    From software spec, you can easily derive test cases based on different outputs. In this case, function's behavior is driven test cases:

1. Print fizz when input is 3

2. Print buzz when input is 5

3. Print fizz buzz when input is 15

4. Print given number

Don't get stressed by writing test spec at first. It does not have to be perfect. It can be always enhanced during TDD cycle.

We can start to create ceedling project named "fizzbuzz_unittest" and create module named "fizzbuzz".


Let's start to write test code based on simple test case. In this case, 4th case would be the simplest. It only requires user input and print that input. To write unit test, you need to remember AAA rule which is Arrange, Act, Assert. Here is an example:


Let's run the test by ceedling test:fizzbuzz. Of course, it will be failed because of no function prototype and definition. Time to create a function based on test result.



Yes, now it should pass: 
Time to write new test case. Let's start with print fizz case. 

Time to validate test case. ceedling test:fizzbuzz.

Previous test case is passed but new test case is failed. It is because current print_fizzbuzz function does not return string type. Let's change print_fizz function to return string type and also handling modulo 3 to return "fizz".



Now, new case is passed but old case is failed. The old test case needs to be refactor. 


Given number should be not fizz, not buzz, not fizzbuzz. So, I pick 1 and change result type int to char* and assert condition:

This is the reason you don't need to write test case perfectly. During TDD, test case is also evolved as well.
Now, back to remaining test cases to add new test case for buzz. 

It is going to fail because print_fizzbuzz function does not have case to handle modulo 5 yet.

Handling modulo 5 now
Passed tests

Adding final test case for fizzbuzz.


You must've been familiar with this pattern by now. Yes, it is failed. Time to implement to handle fizzbuzz case in print_fizzbuzz function.

Finally, print_fizzbuzz function is align with software spec. Since this code is result of TDD, both unit test code and production code are ready!