Test Data Builder Pattern

An automated test data builder?
Some day, test data might be generated auto-magically!

The test data builder pattern is a way of solving a pretty common problem when creating unit tests. When creating tests, you usually need to create test data to run on your system under test (sut). This can easily become unwieldy, when you need to take nested data into consideration.

As you can see, it is very difficult to manage such an object, and to understand what the actual values are referring to. What does the 700 refer to in the Wheel constructor? What about the 25 when creating a Cylinder? Are there any optional parameters that you forgot about? And did you accidentally switch around any of the parameters?

One solution to this problem was the Object Mother pattern. This pattern is simply a factory that can be used to create any test objects you might need. That way, you separate the creation of data from the tests itself. Any time a programmer needs a different variant of that test data, they add a method to the object mother.

One of the problems with this approach is that this class very quickly becomes unmanageable. The more variations you need of a class, the larger that object mother becomes. This is where the test data builder comes into play!

The test data builder

Usually, you don’t really care about most of the data in your test class. What you really want is to control a property, maybe two, of your test data to make sure the input matches the output. The test data builder pattern does exactly that: it generates an object with some reasonable values, and allows you to overwrite them as you see fit. As I mentioned in a previous article, Autofixture can be used to that effect. Autofixture is an incredibly powerful generic test data builder. That means that you can do something like this:

As you can see, you can create a simple car, with all properties automatically filled out. Need more control? You can also tell it to overwrite the brand with the name “Ford”, as we have done on line 4. You can also create many classes with the CreateMany method, as can be seen on line 9. Not only that, but we also feed it a Gearbox for it to use when creating those cars.

Conclusion

I hope that you can see how powerful the test data builder pattern is. Your tests are much more focused, because you no longer are filling information that is usually irrelevant to the test itself. This lowers the required cognitive effort needed in order to understand your test. Your tests are also much shorter, because you need much less code in order to express yourself.

I will be showing you how to use Autofixture and xUnit together in my next article in order to create unbelievably short and concise unit tests. I hope you enjoyed this article, and stay tuned for more!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.