When I was first learning TDD, I’d try to get to the First Step (a failing test) by writing a fully-formed test. But it often took a lot fiddling to get that test to run and fail. Sometimes this was because the production code took several steps to set up. Sometimes it was because the test code wasn’t right.
One of the tricky parts of TDD is that we’re creating two streams of code in parallel: the test code, and the production code. Two things changing at the same time… that’s a hard thing to keep in your head!
That’s where the 3 Laws of TDD come in. They constrain us to change only one thing at a time. Here they are:
It’s hard to tell how they work just from reading them over. So watch the video above! I give a demonstration of the 3 Laws, as they play out in Swift. (Bonus: There’s a mock object, too.)
The next time you TDD a component, go ahead and do it the typical way, by writing the entire test. Observe:
Then try it again, but apply the 3 Laws. Notice the difference. Do you see how this activates even tighter feedback loops?
Remember, getting rapid feedback is a huge benefit of Test Driven Development. So why not dial it “up to 11”?
Give it a try. Then post your questions or observations in the comments below!
Did you like the video? Consider having me teach my TDD for iOS workshop at your company.
Jon is a consultant on Clean Code for iOS, focusing on Test Driven Development, unit testing, refactoring, and design. He's been practicing TDD since 2001. You can learn more about his background, or see what services he can bring to your organization.
Please log in again. The login page will open in a new window. After logging in you can close it and return to this page.