
215
Root Cause
Cut-and-Paste Code Reuse is often the default way to reuse logic. Developers
who focus on details of “how” to do something will often repeat the same code
many times because they cannot (or do not take the time to) focus on the big
picture (the intent) of the test.
A contributing factor may be a lack of refactoring skills or refactoring expe-
rience that keeps developers from extracting the big picture from the detailed
code they have written. Of course, time pressure may also be the culprit that
keeps the refactoring from occurring. As a result, test code grows more compli-
cated over time rather than becoming simpler.
Possible Solution
Once Test Code Duplication has occurred, the best solution is to use an Extract
Method [Fowler] refactoring to create a Test Utility Method (page 599) from
one of the examples and then to generalize that method to handle each of the
copies. When the Test Code Duplication consists of fi xture setup logic, we
end up with Creation Methods (page 415) or Finder Methods (see Test Utility
Method). When the logic carries out result verifi cation, we end up with Custom
Assertions (page 474) or Verifi cation Methods (see Custom Assertion).
We can use an Introduce Parameter [JBrains] refactoring to convert any lit-
eral constants inside the extracted method into parameters that can be passed in
to customize the method’s behavior for each test that calls it.
More simply, we can avoid most Test Code Duplication by writing the Test
Methods in an “outside-in” manner, focusing on their intent. Whenever we need
to do something that involves several lines of code, we simply call a nonexis-
tent Test Utility Method to do it. We write all our tests this way and then fi ll in
implementations of the Test Utility Methods to get the tests to compile and run.
(Modern IDEs facilitate this process by providing automatic method skeleton
generation at a click of the mouse.)
Cause: Reinventing the Wheel
While Cut-and-Paste Code Reuse deliberately makes copies of existing code to
reduce the effort of writing tests, it is also possible to accidentally write the same
sequence of statements in different tests.
Root Cause
This problem is primarily caused by a lack of awareness of which Test Utility
Methods are available. It can also be caused by a predisposition to write one’s
own code rather than reuse code written by others.
Test Code Duplication
Test Code
Duplication