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 2

In part 1 I was able to take an Angular controller written in JavaScript and convert it to a TypeScript file while doing very little to change the code. In this post I am going to explore transitioning that same controller to actually use the features provided in TypeScript. This is how I left off my controller:
declare var angular: any; (function () { 'use strict'; var controller: any = function($scope){ ... } angular .module('app') .controller('controller', controller); controller.$inject = ["$scope"]; })();
While performing the translation from JavaScript to TypeScript, I would make sure at every step that the functionality I expected still worked, so if anything I did broke the system I would change it back and try again with another approach. Also if something seemed like it worked too easily, I would break it on purpose to make sure I wasn't getting a false result through browser caching a previously working fil…

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') …

Gamify TDD

I like it when things that would not normally be associated with games add concepts from games as a way to incentives you to accomplish things. Why simply go for a run if you can have an app that will track you and give you a gold star if you do better than you did the last time? Why go to the coffee shop that only gives you coffee if the other one will give you points that you can redeem for free drinks eventually?

I was recently introduced to CodeSchool, an online training system similar to PluralSight, it has video courses and challenges you can take to prove that you retained what the video taught. CodeSchool also adds badges and tracks to your learning, so as you complete a video and its challenges you get a badge. Complete a collection of courses within a specific discipline and you become a master of that discipline.

Some of these incentives are not tangible and really don't mean much in the real world, but they tend to work for me. If I start working towards a large goal a…