TDD Example

TDD Example

Before starting TDD, we need software spec and test cases. Our 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

Do not spend too much time for writing the test cases. It can be always enhanced during TDD cycle. We can start to create ceedling project named "fizzbuzz_unittest" and create module named "fizzbuzz" image.png

  • Remember AAA(Arrange, Act, Assert) to write a test case

Let's start to write test code based on a simple test case. In this case, 4th case would be the simplest. It only requires user input and print that input. Here is an example: image.png

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. image.png

fizzbuzz.h

image.png

fizzbuzz.c

image.png

re-run the test

Time to write new test case. Let's start with print fizz case. image.png Time to validate test case. ceedling test:fizzbuzz. image.png This is typical routine of TDD process. We write the test case first with bare minimum function implementation and expect to fail and implement only few lines to pass the previously failed test case.

image.png

fizzbuzz.h

image.png

fizzbuzz.c

image.png

re-run the test - first test case is failed

image.png

refactoring: 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. 4th test case should be changed as Print given number that is not "fizz" and "buzz" and "fizzbuzz". Now, back to remaining test cases to add new test case for buzz. image.png

image.png

re-run the test - fail because print_fizzbuzz function does not have case to handle modulo 5 yet

image.png

fizzbuzz.c

image.png

re-run the test

Time to write next test case about fizzbuzz. image.png

image.png

re-run the test - new test case is failed

image.png

fizzbuzz.c

image.png

re-run the test

  • Conclusion

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 at the same time!

Did you find this article valuable?

Support Hyunwoo Choi by becoming a sponsor. Any amount is appreciated!