Test factories
Better way of creating test data
Test data
All forms of testing require known input data which will be compared with the result. If the test input is a single value or small composite it’s not a problem to create it in an ad-hoc manner, directly when it is needed.
But this only works for small inputs.
More complex things, like objects, lists, lists of objects, object graphs require a lot of code to set it up properly. It’s not a problem when done once, but when testing thoroughly there’s a need to do it many times. Each time with small variances.
Abstractions
The case of a lot of commonalities throughout the test data calls for abstracting it away. Building a small library which will create exact data your tests require is the best way to do it.
Test factories
Building test data library is not a problem. The test data is rather simple and generating it is not complicated. But creating such library requires time, time which would be better spent on writing tests alone.
That’s where ready-made factories come to light. There’s a lot of solutions solving that exact problem. Learning how to use them is usually easier than rolling something on your own.
Because most of those test factories have very similar structure, learning one of them translates well into others, be it the same language or not.
I use them all the time and they have saved me a lot of time when ensuring that my tests are hitting all the required corner cases.