Tuesday, November 1, 2016

Building objects for your Unit Tests

When creating unit tests I prefer to use the AAA pattern (Arrange, Act and Assert).  During the Arrange part you usually end up instantiating objects to use for the test.  Depending on the complexity of the objects you are creating this can get to be a little bit of code.  Lets look at the code below:

Note the method BuildContact.  It takes a parameter of an Action<Contact> which would allow you to pass in a lambda expression to further define the properties you want to change on the Contact object for each unit test individually.  This centralizes the logic needed to create the Contact which is helpful but another benefit is what if there was a default value used by every test.  Look at this version of the BuildContact method:

Note the defaults are before the invoking of the action.  This way if a test wanted to override the default values it can.  Normally I create a separate test class for each of the methods I am writing unit tests for.  Using this method above to create the item I am using allows me to create the object with many defaults already set.It wouldn’t be unusual to have several BuildContact methods in different test classes each specific to the needs of that class (method) specifically.