When you practice Test-Driven Development, you know your tests are running.
A coworker (we’ll call him Scott) recently wrote some code and tests without practicing TDD. He wrote the production code first, then wrote the tests. When he ran the test suite, none of the tests failed, so he assumed his newly-written tests had passed and that his newly-written code was well-tested and working correctly. A fair assumption, given the circumstances. However, he didn’t look at the output very closely; otherwise, he would’ve seen that his tests didn’t get executed with the rest of the suite. They didn’t run at all.
Here’s the problem: we work hard to make our assumptions appear to be true.
When we write the production code first, we write tests under the assumption that they will pass. This makes it easier for us to believe the tests did pass after the test suite has run. We always assume the code we just wrote is bug-free, so when we see something that makes it appear that way, we latch on to that idea. It makes us less careful in the verification phase, and this may cause us to miss something, as was the case with Scott.
Turn this story around. Let’s say Scott had written a test first. He then would’ve run the test suite, expecting that test to fail. When he saw that the entire suite of tests passed, he would’ve discovered that his test hadn’t run. Then he could have fixed the problem, run the test suite again, and watched that test fail. From there he could’ve written the necessary code to make the test pass, and he would’ve known with confidence that his test passed and that his code worked correctly.
This isn’t the only reason to do TDD, but it’s one more reason I’ll continue to do it.
Want to learn TDD? Kent Beck’s book,Test Driven Development: By Example is excellent.
How should you start unit testing your app?
Unit testing for iOS can be lonely — most iOS developers don't seem to be doing it. Should you be writing unit tests? What are the benefits of unit testing, anyway? And if it is worth the effort, how do you get started? Enter your name and email in the boxes to get answers to your questions.