I've been trying to learn TDD in Python for a number of months after hearing many programmers, who are much more talented and skilled than I am, extolling the virtues of it. I definitely see the benefit in tests, which I don't argue at all. What I'm having a tough time with is the basic workflow of TDD (as I understand it):
- Think of the next bit of code you need to write.
- For that bit of code, write a test that fails what that bit of code is supposed to achieve.
- Run the program you're testing, asserting that it fails where expected.
- Write the bit of code that you think will make the test in 3 succeed, and repeat until it does.
- Repeat!
The biggest reason I'm having a tough time getting into this flow is the amount of time it takes up. The way I interpret it, for each line of code that may have taken me 30 seconds to write individually takes at least a minute. Consider the following example:
import requests
r = requests.get('http://stackoverflow.com/')
print(r.status_code)
>>> 200
Not a useful block of code certainly, but it completes a task and checks the status of the completion. I wrote that in about 30 seconds in my 'non-TDD' way. The equivalent written in TDD-style would require at least twice as long, because of switching between scripts, writing the test that fails, asserting that the test indeed does fail, then writing the use of the get method, etc. etc.
Then, the second problem I have is this: what use is the test? If I assert that the status_code
is 200, haven't I really just been testing the logic that's written in the requests
module? What do I learn from tests that I absolutely know are going to fail, or absolutely know are going to succeed based on the logical conditions I'm testing within?
One possible problem my thought process has is that I simply haven't learned enough TDD - i.e., maybe it's painful at the beginning to get you in the habit of judiciously writing tests, but eventually it becomes second nature. Even if that is the case though, seamlessly writing a test still takes time, and that amount of time grows as your application grows in complexity.
I'm quite sure that I must be wrong about all of this, as I've read so many people who are "at" the level I want to achieve some day saying such good things about TDD. So, where is my thinking going wrong?!