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.

1 comment:

  1. Our way of life, consumption and building has caused extreme harm to nature. In reality, based on a examine from the Weizmann Institute of Science, we are at a degree of inflection where the mass of all man-made supplies is equal to as} the planet's biomass, and it should double by 2040. But not essentially every thing we build should have a negative influence. The time it takes to print an object will depend on the complexity of the design. Luggage Sets A easy object may take 4-5 hours, while a posh object may take 24 hours.