It is not surprising that code duplication can happen in test code since it is widespread in production code. Tests are often similar in structure, as you may have noticed in several of the code examples. We even used parameterized tests to reduce duplication. A less attentive developer may end up writing duplicate code (copy-pasting often happens in real life, as Treude, Zaidman, and I observed in an empirical study [2021]) instead of putting some effort into implementing a better solution.
Duplicated code can reduce the productivity of software developers. If we need to change a duplicated piece of code, we must apply the same change in all the places where the code is duplicated. In practice, it is easy to forget one of these places and end up with problematic test code. Duplicating code may also hinder the ability to evolve the test suite, as mentioned earlier. If the production code changes, you do not want to have to change too much test code. Isolating duplicated code reduces this pain.
I advise you to refactor your test code often. Extracting duplicate code to private methods or external classes is often a good, quick, cheap solution to the problem. But being pragmatic is key: a little duplication may not harm you, and you should use your experience to judge when refactoring is needed.
Leave a Reply