While browsing / playing in some other teams’ projects in our company, I stumbled across a neat construct that I hadn’t seen before in unit tests – Simply Test Data. Using this framework you can construct some fake objects in a fluent and easy to read manner.
Similar to other fake data frameworks like NBuilder, this framework allows you to define methods you can reuse to create and manipulate test objects to be used in your unit tests. The fluent, expressive interface makes your tests easy to read and understand, helping other developers figure out what’s going on. Here’s a quick example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
The above example seems a bit useless – we’re writing an entire method to set one property! Sure, but this makes a lot more sense when you’re doing some complicated set up.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Here we’re returning Actions, which allow us to chain these little helper methods together to build the test object we want. Now any time we want to make Greeting objects, we can use these few methods in an expressive way in all of our tests.
What if you always want to apply the same transformation every time you create the same type of object? We’ve got you covered!
Now every time you create a Greeting object with TestData, this transform will be applied.
You can copy-pasta the code for SimplyTestData from the github page.