Archive for the ‘Patterns & Frameworks’ Category

Unit tests: expose bugs and spend less time fixing them!

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 < 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!

Dependency injection with Spring.NET

Hands-on introduction on how to configure dependency injection using Spring.NET

In a previous post I’ve discussed a simple n-tier approach using a Facade and Dao pattern. The Facade provides a single access point for the business tier, and wraps a data access object that encapsulates the implementation of the persistence mechanism, separating the concerns.

I also mentioned that these objects introduce a large dependency (high coupling) as the Facade does not function without the Dao. I will now show you how this dependency can be overcome, by injecting the Dao into the Facade using the Spring.NET framework.

In the following example we will create a simple web management tool for a Zoo (inspired by amazedsaint). The tool needs to list all animals and caretakers, and allow the manager to rename animals or to assign one or more caretakers to an animal.

We start out by creating the business entities:


public class Caretaker

{

public string Name { get; set; }

public int Age { get; set; }

}

public abstract class Animal

{

public string Name { get; set; }

public IList<Caretaker> Caretakers { get; set; }

}

public class Lion : Animal { }

public class Elephant : Animal { }

We will also create a Facade which allows consumers to have a good understanding of the class library without having to worry about the exact implementation. Therefore, a good practice is to set up an interface:


public interface IZooManagement

{

IList<Animal> GetAllAnimals();

IList<Caretaker> GetAllCaretakers();

void RenameAnimal(Animal a, string newName);

void AssignCaretaker(Animal a, Caretaker c);

}

This should cover all requirements. The animals and caretakers will be stored in some kind of data store, so we’ll create a data access object (Dao) that will handle this for us. We haven’t decided on which type of data store or which ORM to use, so for now, let’s not worry about its implementation and create the interface:


public interface IZooDao

{

IList<Animal> GetAllAnimals();

IList<Caretaker> GetAllCaretakers();

void UpdateAnimal(Animal a);

}

Ok, now let’s implement the Facade. For the sake of simplicity, I will leave out any validation or error handling. Eventually, the minimal implementation will look much like this:


public class ZooManagement : IZooManagement

{

private IZooDao dao;

public virtual IZooDao Dao

{

set { dao = value; }

}

public IList<Caretaker> GetAllCaretakers()

{

return dao.GetAllCaretakers();

}

public IList<Animal> GetAllAnimals()

{

return dao.GetAllAnimals();

}

public void RenameAnimal(Animal a, string newName)

{

a.Name = newName;

dao.UpdateAnimal(a);

}

public void AssignCaretaker(Animal a, Caretaker c)

{

a.Caretakers.Add(c);

dao.UpdateAnimal(a);

}

}

The persistence mechanism has now completely been abstracted from the Facade. Also notice that the Facade does not instantiate a Dao: the property allows us to “inject” the Dao implementation and completely remove the dependency (this can also be done using a constructor parameter).

We now need to find a good way to inject the Dao into the Facade, and this is where the Spring.NET framework provides additional support, as one of its many features allows you to set up dependency injection through configuration.

Before we configure the dependency injection, let us create a “dummy” Dao, one that does not really access a data store, but holds a list of animals and caretakers internally:


public class DummyDao : IZooDao

{

private IList<Animal> animals;

private IList<Caretaker> caretakers;

public DummyDao()

{

animals = new List<Animal>();

animals.Add(new Lion() { Name = "Simba" });

caretakers = new List<Caretaker>();

caretakers.Add(new Caretaker() { Name = "Leo", Age = 25 });

}

public IList<Animal> GetAllAnimals()

{

return animals;

}

public IList<Caretaker> GetAllCaretakers()

{

return caretakers;

}

public void UpdateAnimal(Animal a)

{

throw new NotImplementedException();

}

}

If you want to use the Spring.NET framework, you will first need to add a reference to your web project. The latest version can be downloaded here. Next, you’ll need to configure Spring.NET in the Web.config:


<sectionGroup name="spring">

<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>

<sectionGroup name="child">

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>

</sectionGroup>

</sectionGroup>

<spring>

<context name="ParentContext">

<resource uri="config://spring/objects"/>

</context>

<objects xmlns="http://www.springframework.net">

<object id="ZooDao" name="ZooDao" type="TheseDays.Business.DAL.DummyDao, TheseDays.Business">

</object>

<object id="ZooManagement" name="ZooManagement" type="TheseDays.Business.ZooManagement, TheseDays.Business">

<property name="Dao">

<ref local="ZooDao"/>

</property>

</object>

</objects>

</spring>

The first part is standard and announces the Spring.NET configuration. The second part is where the magic happens: the spring/context section is necessary for Spring to create its application context, and the spring/objects section allows you to configure the resources.

The object configuration is pretty straightforward: we tell Spring.NET we want to create an object of type ZooManagement (our Facade) and to set its property with an object we also configured, an object of type DummyDao.

Once we have implemented an actual Dao (rather than a dummy one), in order to start using it all we need to do is reconfigure its type. For example, if we would create a RealDao that also implements the IZooDao interface, and we need to pass a connection string to the constructor, the configuration of the Dao would look like this:


<object id="Dao" name="Dao" type="TheseDays.Business.DAL.RealDao, TheseDays.Business">

<constructor-arg name="connectionString">

<value>Server=.;Initial Catalog=Zoo;User=ZooUsr;Password=ZooPwd;Application</value>

</constructor-arg>

</object>

In the web application we can then access the ZooManagement Facade through the Spring’s application context. Here’s a demonstration of a small helper class I often use:


public class ApplicationContextHolder

{

private static ApplicationContextHolder instance = new ApplicationContextHolder();

public static ApplicationContextHolder Instance

{

get { return instance; }

}

private IApplicationContext applicationContext;

private IZooManagement zoo;

private ApplicationContextHolder()

{

applicationContext = ConfigurationManager.GetSection("spring/context") as IApplicationContext;

zoo = applicationContext.GetObject("ZooManagement", typeof(ZooManagement)) as IZooManagement;

}

public IApplicationContext ApplicationContext

{

get { return applicationContext; }

}

public IZooManagement Zoo

{

get { return zoo; }

}

}

Now you can access the ZooManagement in the web pages with a single line of code:


IZooManagement zoo = (ZooManagement)ApplicationContextHolder.Instance.Zoo;

Surely a nice feature when you’re building your own framework!

You can download the full source code of the example here.