The Three Rules of TDD

Robert C. Martin (“Uncle Bob”) provides a concise set of rules for practicing TDD.[9]

  1. Write production code only to pass a failing unit test.

  2. Write no more of a unit test than sufficient to fail (compilation failures are failures).

  3. Write no more production code than necessary to pass the one failing unit test.

Rule #1 says to write tests first—understand and specify, in the form of a unit test example, behavior you must build into the system.

Rule #2 says to proceed as incrementally as possible—after each line you write, get feedback (via compilation or test run) if you can before moving on. When test-driving a RetweetCollection class, we stop as soon as we write this much of a first test:

c3/1/RetweetCollectionTest.cpp
 
#include "gmock/gmock.h"
 
 
TEST(ARetweetCollection, IsEmptyWhenCreated) {
 
RetweetCollection retweets;
 
 
}

We haven’t yet defined RetweetCollection, so we know that this one line of test code shouldn’t compile. We write the code that defines the RetweetCollection class and recompile until we get it right. Only then do we move on to writing the assertion that demonstrates the collection is empty.

Rule #2 is controversial and by no means universally accepted as a TDD standard. In C++, it might not be effective if compilation requires you to wait long. You might also find it’s more effective to flesh out the design of a complete test first. But before you abandon the rule, give it an honest effort. (As a long-time TDD practitioner, I employ rule #2 on a case-by-case basis.)

Rule #3 says to write no more code than your tests specify. That’s why rule #1 says “to pass a failing unit test.” If you write more code than needed—if you implement behavior for which no test exists—you’ll be unable to follow rule #1, because you’ll soon be writing tests that immediately pass.

As you grow in your mastery of TDD, you’ll find cases where it’s near impossible to lead with a failing test. (The following section, Getting Green on Red, talks about this further.)

Learning by following the rules will help you later understand the adverse implications of breaking them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.55.198