You may have seen the 3 steps of “the TDD waltz”: Fail, Pass, Refactor. There are many ways to do it wrong! Two common mistakes are:
So let me give you 3 reasons why it’s important to refactor tests.[This post is part of the series TDD Sample App: The Complete Collection …So Far]
Test code isn’t the forgotten cousin of production code. In fact, Robert Martin says that good tests are more valuable than production code. If you have a rich suite of tests, you can derive production code that satisfies them. But going the other way — deriving test code from production code — is much harder.
Like any code, tests can rot if neglected. Treat test code with the same respect you give to production code. If you refactor production code, why wouldn’t you refactor tests?
(You do refactor production code, don’t you? And I don’t mean “changing things” or “rewriting”. I mean real refactoring, by the book.)
As with any code, readability is vital. Why? Because code isn’t just for computers; it’s for people. Think of the next person who will have to read your tests. (…That person may be you! In which case, you’re doing your future self a favor.)
A big part of readability is hiding details in methods with well-chosen names. Good names express what something does, or why. The details of how are there in the method, but only if you need to see them.
Refactor tests to have good names, good variables, and well-named helper methods. The better a test expresses itself, the less trouble you’ll have maintaining it.
Production code keeps changing. When that happens in a way that requires tests to also change, which would you rather do?
Some people say that test code shouldn’t be DRY (Don’t Repeat Yourself). There is a balance to hit: test code shouldn’t have layers upon layers of abstractions. But that shouldn’t be an issue, because good test code is simple to begin with:
So I’ve found that one layer (occasionally two) of tiny helper methods helps keep tests easy to maintain.
Renaming, moving things around, extracting methods… This is all basic refactoring that applies to any code, including test code. So don’t be afraid to refactor tests.
Next time, I’ll show you 3 steps to apply when refactoring tests.
Are your tests “set and forget”? When was the last time you refactored any tests? Share your thoughts, experiences and questions in the comments below.
Programming was fun when I was a kid. But working in Silicon Valley, I saw poor code lead to fear, with real human costs. Looking for ways to make my life better, I learned about Design Patterns, Refactoring, and Test-Driven Development (TDD). Programming became fun again! I've now been doing TDD in Apple environments for 17 years. I'm committed to software crafting as a discipline, hoping we can all reach greater effectiveness and joy.
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.