mobile menu icon

Remove data structures noise from your tests with builders

Published by Carlos Blé on 23/07/2015

Clean Code, TDD, Testing, Refactoring, Code Smells, Builders


Among other qualities good tests should be easy to read, quick to understand. When the test requires complex data structures to be sent to the SUT or to be part of a stubbed answer, it takes longer to read. Moreover those structures use to evolve as the production code does causing too many changes in the tests in order to adapt them. An indirection level in between the test and the production code helps improve readability and ease of maintenance. Builders come to the rescue. I often overload builder methods to support several data structures and then apply the conversions internally.

As an example, this is the setup of one of our tests before the final refactor:

Imagine how ugly those tests were before writing the ACatalog builder. And this is the test after the builder was overloaded to supply a more comfortable API:

Originally published in Carlos Blé's blog.

Volver a posts