Hands-on introduction to creating unit tests that cover your application’s business logic
An extra effort and more code: two major drawbacks that often discourage developers from writing unit tests. They seem hard to write and little to contribute or at least that is what I first experienced when I started using them. And although I still don’t consider myself to be an expert in the field of test-driven development, I have not given up and can say: unit tests are a real time saver. Rather than walking through a long list of benefits, let’s write some code and see for ourselves..
Before you can write a unit test you obviously need to have a chunk of code or some business logic that requires testing. The following example shows you how to add a unit test after writing your initial code and how you can alter the unit test before writing any additional code (e.g. in a second iteration).
Important to note: although the example is created in C# with the Visual Studio unit-testing framework, the principles can be applied to any given library in your preferred programming language.
The full source code of the example can be downloaded here.
Example: Testing the shopping basket of a web shop
Let’s say you are working on a web shop and you are asked to implement some logic that calculates the total price of a shopping basket. You’ve created the shopping basket and price calculation logic in the business tier:
public class WebshopFacade
{
public void AddProductToBasket(ShoppingBasket basket,
Product product)
{
basket.Add(product);
UpdateBasketPrice(basket);
}
public void UpdateBasketPrice(ShoppingBasket basket)
{
double totalPrice = 0;
foreach (ShoppingBasketItem item in basket.GetItems())
{
totalPrice += item.Product.UnitPrice * item.Amount;
}
basket.TotalPrice = totalPrice;
}
}
The code is pretty straightforward: the web shop can create a basket but to add an item it needs to call the façade which will than update the basket’s total price. Now, before creating a web page (and I know you want to) it’s a good practice to set up a unit test. Why? If there are any coding errors in the shopping basket or its price calculation, you want to expose these bugs right now, and not by experiencing strange issues when creating the web page which will eventually have you debug the web application. The unit test may already save you from losing precious time, and surely you want to hold on to it for future testing when the price calculation logic becomes more complicated.
Test method 1: Initial price of the basket
Ok, let’s start out with a basic yet crucial test: you want to make sure that when the web shop creates a basket, the initial total price is zero. You may laugh, but your customers won’t if this is not the case!
[TestClass]
public class ShoppingBasketTest
{
public ShoppingBasketTest()
{
}
[TestMethod]
public void TotalPriceOfEmptyBasketMustBeZero()
{
ShoppingBasket basket = new ShoppingBasket();
Assert.AreEqual(0, basket.TotalPrice, "Expected total price to be zero for empty basket");
}
}
That wasn’t so hard, was it? Running all tests in Visual Studio takes only a few seconds and for me it resulted in a test run completed, results: 1/1 passed. Sweet, an instant confidence boost!
Test method 2: Adding products to the basket
Let’s move on and add a test method that ensures products can be added to the basket:
[TestMethod]
public void ProductsCanBeAddedToTheBasket()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();
for (int i = 0; i < 50; i++)
{
facade.AddProductToBasket(basket, mocks.CreateProduct());
}
int totalUnits = 0;
foreach (ShoppingBasketItem item in basket.GetItems())
{
totalUnits += item.Amount;
}
Assert.AreEqual(50, totalUnits, "Expected 50 units in the basket after adding 50 random products");
}
In this test 50 random products are added to the basket, and then the test does a recount by looping through the basket’s items. As the test method cannot create products directly (nor can the web shop for that matter) a mock factory is used to create mock objects, in this case products.
And believe it or not, when I first ran the test it failed because of a bug in the basket. In Visual Studio you can add a breakpoint inside any test method and instantly debug the test method, so I was able to resolve the issue in no time!
Test method 3: Price calculation
Finally, you can add a test method which ensures the total price is calculated correctly:
[TestMethod]
public void BasketTotalPriceIsCalculatedCorrectly()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();
double expectedTotal = 0;
for (int i = 0; i < 50; i++)
{
var product = mocks.CreateProduct();
facade.AddProductToBasket(basket, mocks.CreateProduct());
expectedTotal += product.UnitPrice;
}
Assert.AreEqual(Math.Round(expectedTotal, 2), Math.Round(basket.TotalPrice, 2), "Expected total price does not match basket's total price");
}
The code is mostly copied and pasted from the previous method, but here the price calculation is somewhat mimicked. It may seem obvious that this test will pass, but when you make further progress in developing the basket, this test method can fail, and it will expose any bugs that were introduced by your (or someone else’s) changes.
Another way of testing this logic would be to create some specific products, and to hard code the expected total price. This could include special situations that don’t frequently occur but are part of the business logic, e.g. discounts for certain products, discounts for a specific amount of products, etc.
Creating a unit test before writing any code
The unit test now covers the basic functionality of the basket and you might decide to start a second iteration in which you introduce removal of products or discount logic. In either case you can initiate this iteration by creating new unit tests or updating the existing one allowing you to focus on the requirements before writing any code.
You can start by changing the “interface” of the façade, by adding a method for product removal:
public void RemoveFromBasket(ShoppingBasket basket,
Product product)
{
throw new NotImplementedException();
}
And now you can add new test methods that validate the product removal logic:
[TestMethod]
public void ProductsCanBeRemovedFromTheBasket()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();
var addedProducts = new List
();
for (int i = 0; i < 50; i++)
{
var product = mocks.CreateProduct();
facade.AddProductToBasket(basket, product);
addedProducts.Add(product);
}
for (int i = 0; i &amp;amp;amp;amp;amp;lt; 25; i++)
{
var remove = addedProducts[i];
facade.RemoveFromBasket(basket, remove);
addedProducts.Remove(remove);
}
int totalUnits = 0;
foreach (ShoppingBasketItem item in basket.GetItems())
{
totalUnits += item.Amount;
}
Assert.AreEqual(25, totalUnits, "Expected the basket to have 25 remaining units after removal");
}
[TestMethod]
[ExpectedException(typeof(ShoppingBasketException), "Expected shopping basket exception to be thrown")]
public void ProductMustExistInBasketOnRemoval()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();
facade.RemoveFromBasket(basket, mocks.CreateProduct());
}
Obviously the unit test will fail if you run it before you have written the actual implementation, but for sure you will gain a great deal of insight in how to set up any interfaces, how objects should behave or interact, how exceptions are thrown, etc.
Try it out yourself!
A demo, including the example’s full source code can be downloaded here. You can run the tests in Visual Studio by pressing CTRL-R A or through the menu as shown in the screenshot below. If you are new to unit testing and can use a little practice, I strongly recommend that you try and write the code for product removal, and see if you can make the failing unit test pass again.
Final considerations
• Any unit tests that you create are there to stay and the more complex a module becomes the more often you will find that bugs are exposed when the module is changed or re-factored, simply by rerunning the tests
• By creating advanced unit tests you are to mimic and validate every possible in- and output of a certain module, allowing you to immediately recognize and debug the most specific / exotic situations when a test fails
• Unit tests may seem like a lot of code to write, but most of the time you are just writing the consuming code that has to be implemented anyway
• Unit tests offer great insight in how a module behaves or is to be used. Developers that are not familiar with the code can walk through the tests as it were code documentation
Hope this helps!


Recent Comments