5.3.4 Test data builder
Course subject(s)
Module 5: Test Code Smells
In practice, creating fixtures (i.e., the arrange part of the test) is maybe the most complex part in a test code. After all, some of our systems are highly complicated and require lots of data to start working.
So, it is common to face long methods that basically set up objects:
Invoice i1 = new Invoice(100.0, new User(“Mauricio”, new Address(“Netherlands”)), …)
Besides being complex and hard to understand, these pieces of code are highly prone to change. Suppose that the Invoice class changes. For example, it starts to receive a new parameter in the constructor. The developer would have to then go back to all the test classes that use it and add this new parameter.
A new way to solve this problem is to then encapsulate the creation of the test object in another class, that is responsible only for the creation of the object. This design pattern is called Test Data Builder, and it is a derivate of the Builder pattern.
The following links provide clear explanations and implementation examples of how this pattern can be done:
- Test Data Builders: an alternative to the Object Mother pattern, by Nat Pryce: http://www.natpryce.com/articles/000714.html.
- Some frameworks, such as factory_bot (https://github.com/thoughtbot/factory_bot, for Ruby language) and Fixture Factory (https://github.com/six2six/fixture-factory, for Java) help developers in creating test data.
Further reading:
You can find more about the Builder pattern and other design patterns at:
- Gamma, E. (1995). Design patterns: elements of reusable object-oriented software. Pearson Education India.
Automated Software Testing: Practical Skills for Java Developers by TU Delft OpenCourseWare is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Based on a work at https://online-learning.tudelft.nl/courses/automated-software-testing-practical-skills-for-java-developers/.