#TIL: SimplyTestData

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
//given a class like this
public class Greeting
{
  public string Message { get; set; }
}

//you can generate an object like this
TestData.Create<Greeting>(HelloWorld);

//where HelloWorld is a simple Action delegate
private void HelloWorld(Greeting greeting)
{
  greeting.Message = "Hello, World!";
}

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
TestData.Create<Greeting>(Greeting("Hi"), To("Alice"), And("Bob"), 
  And("Chad"));

//with the following methods
private Action<Greeting> Greeting(string message)
{
  return greeting => greeting.Message = message;
}
private Action<Greeting> To(string friend)
{
  return greeting => greeting.Message += ", " + friend;
}
private Action<Greeting> And(string friend)
{
  return greeting => greeting.Message += " and " + friend;
}

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!

1
TestData.SetPermanentCustomizations<Greeting>(g => g.Message = "Hello");

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.

Comments