Skip to main content

Unit Test Builder Pattern

I was recently introduced to a pattern for setting up Unit Tests with test data that I really like. It is called the Builder Pattern. It abstracts away the setup of your test data so that if properties or structure of your test data changes, you can make that change in one place and it will update all tests that would have otherwise been broken. It also makes it more clear exactly what you are testing for because you take the specific variables in your test data out of the tests and into the builder, leaving behind the intent of the test.

Following the Arrange, Assert, Act layout for a Unit Test, the Builder Pattern helps you define what goes into the Arrange section, and makes that section more readable and adaptable to change. Lets look at an example of what some current unit tests might look like.

[Test]
public void TaxAmount_CountryEngland_Returns0()
{
 var testData = new TestData()
 {
  Country = "England"
 };

 var result = Target.GetTaxAmount(testData);

 Assert.AreEqual(0, result);
}

[Test]
public void TaxAmount_CountryUnitedStatesANDCityNewYork_Returns9()
{
 var testData = new TestData()
 {
  Country = "USA",
  City = "NewYork"
 };

 var result = Target.GetTaxAmount(testData);

 Assert.AreEqual(9, result);
}

[Test]
public void TaxAmount_CountryUnitedStatesANDCityLosAngeles_Returns7()
{
 var testData = new TestData()
 {
  Country = "USA",
  City = "LosAngeles"
 };

 var result = Target.GetTaxAmount(testData);

 Assert.AreEqual(7, result);
}

Each test is building up an object that will be evaluated to determine the tax amount. Based on the rules, you get different amounts. All of these tests share 1 property in common and 2 share another 1 in common. The way these tests are constructed shows what data the tests need to get the desired results, but if Country was renamed or its type was changed to an Enum then you would need to fix that in all 3 tests. Following the Builder Pattern will help minimize the number of places that would need to be changed.

I start by Creating a new Class that will be the Builder for my TestData, this has a Build function that
will return my test data.
public class TestDataBuilder
{
 private TestData data;

 public TestDataBuilder()
 {
  data = new TestData();
 }

 public TestData Build()
 {
  return data;
 }
}

Then I create methods for each of the pieces of test data that are important for my tests. I start by writing a method for Country equal to England and another for Country is USA.
 public void WithCountryEngland()
 {
  data.Country = "England";
 }
 
 public void WithCountryUSA()
 {
  data.Country = "USA";
 }

Next I write Methods for City.
 public void WithCityLosAngeles()
 {
  data.City = "Los Angeles";
 }
 
 public void WithCityNewYork()
 {
  data.City = "New York";
 }

Notice that I don't write a method for City equal London, because at least to this point I don't need that method. There is no logic being tested against London. I only write functions for what I need to.

Now my tests will look like this:
[Test]
public void TaxAmount_CountryEngland_Returns0Percent()
{
 var testDataBuilder = new TestDataBuilder();
 testDataBuilder.WithCountryEngland();

 var result = Target.GetTaxAmount(testDataBuilder.Build());

 Assert.AreEqual(0, result);
}

[Test]
public void TaxAmount_CountryUnitedStatesANDCityNewYork_Returns9Percent()
{
 var testDataBuilder = new TestDataBuilder();
 testDataBuilder.WithCountryUSA();
 testDataBuilder.WithCityNewYork();

 var result = Target.GetTaxAmount(testDataBuilder.Build());

 Assert.AreEqual(9, result);
}

[Test]
public void TaxAmount_CountryUnitedStatesANDCityLosAngeles_Returns7Percent()
{
 var testDataBuilder = new TestDataBuilder();
 testDataBuilder.WithCountryUSA();
 testDataBuilder.WithCityLosAngeles();

 var result = Target.GetTaxAmount(testDataBuilder.Build());

 Assert.AreEqual(7, result);
}

I have successfully removed any references to the specific properties on TestData and reduced the number of places a given property needs to be changed to keep these tests working if the TestData class changes. Even if the properties that these tests are concerned with never change, I have still been able to move the constructor for TestData out of each of these tests and into the TestDataBuilder constructor. If TestData in the future needs parameters inserted through its constructor, I can change my TestDataBuilder in 1 place and these tests will continue to work rather than need to change that in all of these tests.

You can then use the Fluent approach and return a TestDataBuilder type out of your data definition methods, allowing you to chain them together.
 public TestDataBuilder WithCountryUSA()
 {
  data.Country = "USA";
  
  return this;
 }
 
 public TestDataBuilder WithCityLosAngeles()
 {
  data.City = "Los Angeles";
  
  return this;
 }

Then you can also have the TestDataBuilder convert iteself into TestData and remove the Build function as long as you implicitly tell the TestDataBuilder that you want it as TestData.
 public static implicit operator TestData(TestDataBuilder builder)
 {
  return builder.Build();
 }

Leaving us with our final tests looking like this:
[Test]
public void TaxAmount_CountryEngland_Returns0Percent()
{
 TestData testData = new TestDataBuilder()
                            .WithCountryEngland();

 var result = Target.GetTaxAmount(testData);

 Assert.AreEqual(0, result);
}

[Test]
public void TaxAmount_CountryUnitedStatesANDCityNewYork_Returns9Percent()
{
 TestData testData = new TestDataBuilder()
                            .WithCountryUSA()
                            .WithCityNewYork();

 var result = Target.GetTaxAmount(testData);

 Assert.AreEqual(9, result);
}

[Test]
public void TaxAmount_CountryUnitedStatesANDCityLosAngeles_Returns7Percent()
{
 TestData testData = new TestDataBuilder()
                            .WithCountryUSA()
                            .WithCityLosAngeles();

 var result = Target.GetTaxAmount(testData);

 Assert.AreEqual(7, result);
}

I have begun using this approach in my current project and have found it has already saved me time. Once you have a few of the Builder methods defined you will likely find that you can reuse them when writing new tests. You end up with less complex, less fragile, and more reusable Tests and Test code. I think its a really great way to setup your tests.

Comments

Popular posts from this blog

Converting a Large AngularJS Application to TypeScript Part 1

I work on a project that uses AngularJS heavily. Recently we wondered if using a preprocesser like CoffeeScript or TypeScript for our JavaScript would be beneficial. If our team is going to switch languages, we would need to be able to convert existing code over without much pain and we would have to find enough value in switching that it would be worth the conversion. I had read an article that stated that because TypeScript is a SuperSet of JavaScript, you could convert a plain JavaScript file to TypeScript by changing the extension to .ts and not much else would need to change. I wanted to test out this claim, so I took a file that I was familiar with, an Angular Controller, and tried to convert it to TypeScript to see how much effort it would take and then try to figure out where we would benefit from using TypeScript. This is what the controller JavaScript file looked like to start out with: ( function () { 'use strict' ; angular .module( 'app'

Interns: Taking off the training wheels

My intern team has been working for several weeks now on our new website. We have already completed one deployment to production and are finalizing our second one. We started with a plan to release often adding small bits of functionality as we go and so far that plan has been working really well. We already feel like we have accomplished a lot because we have completed many of our project's requirements and should easily be able to complete the rest giving us time to do even more than just the original requirements. One of the things I have had some difficulty balancing has been how much to lead the interns and how much to let them figure out on their own. In deciding what our team process should be and how we should allocate our time, I think it was important for me to do more leading. I saw some deficiencies in how we were currently working and brought up some ideas for how we could address them. We had moved into spending all our time just working through stories and did not

My idea for Hearthstone to add more deck slots

Recently someone asked the Blizzard developers for more slots for decks in the game Hearthstone. The response was that they are talking about it and looking into it, but no decision has been made yet. One of the concerns over adding deck slots is that it could complicate the UI for Hearthstone and make it more difficult for new players to understand. I have what I think would be a good solution to add more deck slots without increasing the learning curve for the game much if at all. First I would take a look at the current selection screen for starting to play a game. It defaults to showing the decks that are custom built by the player if they have any custom decks, and there is an option to page over to the basic decks. This basic deck screen is perfect for how I would change this process. Instead of having 2 pages of decks, 1 for basic and 1 for custom, you would just see the select a Hero screen. Then once you selected the Hero you wanted, you would see all of the decks that