Saturday, January 4, 2014
As the name suggests, TDD is a programming "style" that depends on test cases for its structure and development process. TDD is related to the extreme programming concept. It has basically the following steps:
1. Write automated test cases
2. Check if the test fails. The result will guide the production code
3. Run the test cases again
4. Clean up the code
Of course, it not very easy to understand this concept just with theorical explanations. Taking that into account, here we have a practical example in Python:
1. Python installed. Download it here.
Note: This article assumes that you know the basics for Python. If you want to know some more about it, read this.
For this example, we'll create a simple Python program to check if a number is prime.
Using some text editor like notepad++, open a new file and copy the following code. Then save the file as "prime_test.py".
If you run this, you'll obviously have errors, since there is no "prime_numbers" module to import. But this shows how TDD works: You write the test before anything. Basically, the error messages tell you what to do next. In this example, the error is: ImportError: No module named prime_numbers. So, the first thing to do is to create the prime_numbers module. Let's do it. Create another Python file and copy the following code:
Now run the test again. Of course, it's going to fail again. We don't have the methods working yet. The trick with TDD is to make the test pass. So, in order to do that, we have to write the check_prime method:
Run the test again. Check the message and you'll know what to do next. The error message says: AssertionError: True is not false. So, you need the method to return false when a number is not prime. You can do that this way:
Run the test cases again and you'll see that they all pass. That's how you know that you are finished. As you can see, the code is driven by the test cases.
One interesting point about TDD is that you may en up writing more code in the test cases than in the actual program. Of course, there are some advantages in this programming style (from my point of view):
- You have your code very well structured.
- The coverage is often higher than 90%.
- It prevents the developer from making some mistakes.
- Once you get used to it, TDD helps you to develop in an easier way.
Among the disadvantages I could mention:
- The quantity of code for test cases can be huge in large projects.
- It can be distracting to focus on the test cases.
- You have to worry about writing the tests well. Test cases have bugs too.
- You might feel that you are wasting your time writing too many test cases...