Author Archive

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!

Why Umbraco suits us

It has only been a couple of months since we first started using Umbraco, an open-source CMS built on top of the .NET platform, and a lot of my colleagues will agree when I say that we have grown extremely fond of it. Why, you ask? Well, let me explain a few things.

Finding the right CMS is a challenge

Finding a CMS that suits your needs – not to mention fully embracing one – is not an easy task. It is hard to get your hands on a descent comparison and research is very time consuming as you really need to get your hands dirty. If you are somewhat wary and cautious about using a CMS, you are right, it is to be a tool that assists you in creating and maintaining websites, and it should never dictate the way you handle things as you probably already have a methodology or framework in place. And that is exactly what we have found in Umbraco: a reliable, user-friendly and extensible platform which drastically reduces development time and really fits into our projects.

Umbraco is easy, extensible and reduces development time

After completing several projects with Umbraco, we are very pleased with the results and would like to emphasize the following:

  • Umbraco is easy to learn. Within days you are able to grasp its concept and developers will be writing custom XSLT for dynamic content such as a news pages, FAQ’s, ..
  • As Umbraco is based on ASP.NET, most developers will be very familiar with the environment and configuration settings which eases development and deployment
  • Umbraco has an active community: http://our.umbraco.org/
  • A project can be implemented without writing a single line of .NET code. You may have to write some XSLT or install a package, but you will save a considerable amount of development time nonetheless
  • Umbraco is extensible in many ways, from writing custom XSLT and .NET user controls to installing packages and integrating its API or event-driven model.

Most importantly, its extensibility allows us to choose which parts of an application we wish to implement using Umbraco while we are still able to implement the parts we don’t see fit in the exact same way we would implemented these in other situations.

Completed projects

Although we still have several projects in the pipeline, we would already like to share some of the projects that have been fully implemented using Umbraco:

Plans for the future

We plan to do much more with Umbraco, and the first thing we want to do now is tweak our development environment and make Umbraco integration even easier:

  • Add an abstraction layer to our framework that will abstract the Umbraco API integration and provides a set of global helper classes for Umbraco
  • Create a template solution for Visual Studio that contains a pre-configured Umbraco install and includes our framework projects
  • Moving the template solution to Microsoft’s Web Platform Installer, allowing our developers to install the latest version of the template in no time. See also: http://bit.ly/aj2Uwm

As you can see, many of us have become strong believers and if you are considering using Umbraco as your CMS or you are a strong believer yourself we are always glad to hear from you.

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.

Basic architecture of an ASP.NET / Silverlight web application

An important aspect of web development is choosing the right application architecture or framework, one that is flexible, easy to maintain and well understood by its developers.

The (ASP) .NET framework already offers a lot of built-in features which greatly reduce the overhead of common programming activities, and a content management system delivers out-of-the-box components and back-end functionality.

When it comes to custom development, it is of course the developer’s responsibility to apply best coding practices and common design patterns when and wherever possible, preserving high flexibility and maintainability in the application’s overall architecture.

Having this said, I would like to share with you a simple n-tier approach which is currently being implemented in one of our ongoing projects. As the framework fits the project, in this particular case there is no need for a CMS. Without going into too much detail, the use-cases indicate the need of data storage and retrieval (CRUD operations on a few persistent objects), email notification, dynamic generation of images and (multi-lingual) localization support.

An ASP.NET web application hosts 2 Silverlight features which provide a media player and a deep zoom component. Both the web and Silverlight applications need to access common business objects and a persistence mechanism, albeit in different use-cases.

Let’s take a closer look at the framework:

The application’s main class library, storing all business objects and business logic provides a single point of access for client applications: a Façade object. The Façade implements a clear interface for common tasks, while hiding the actual implementation.

As you may or may not know, a Silverlight application does not have direct access to a class library, but rather makes asynchronous calls to one or more (web) services. Great progress is currently being made to ease this challenge for developers (WCF RIA Services and ADO.NET data services) but we have chosen to use a more classic approach by setting up a WCF service. Much like the Façade, this service provides a clear interface for common tasks, although limited to the tasks required by the Silverlight applications. However, the actual implementation still resides in the Façade enhancing the solution’s flexibility (i.e. some tasks may be shared with the web application).

The persistence mechanism is abstracted by a data access object or DAO referenced only by the Façade, greatly reducing any dependencies. Much unlike the active record pattern which provides business objects with CRUD operations, the DAO provides these operations for a subset or all business objects.

Some extra hints & tips:

  • As you may have noticed, there is still a strong dependency between the Façade and the DAO. This dependency can easily be overcome by dependency injection (i.e. by using the Spring.NET framework, and injecting the proper DAO at runtime by means of configuration)
  • Although this example mentions just one façade and DAO, it is recommended to set up multiple instances, each encapsulating separate units of logic or data stores. Facades can easily be set up to interact with each other, and a DAO is commonly used to abstract a single data store.
  • Façade and DAO tend to grow large as they often encapsulate the implementation of large units of work. Implementing them as a singleton greatly reduces performance overhead when consumption increases.
  • By letting persistent business objects inherit from a base entity object the DAO can provide generic methods for CRUD operations, and so can the Façade
  • By unit testing against the Façade, you are able to test most (if not all) of the business logic

Some code fragments:

Facade & DAO interfaces:


public interface IBusinessFacade

{

IList<Company> SearchCompanies(CompanySearchCriteria criteria);

Company GetCompanyById(string companyId);

IList<Employee> SearchEmployees(EmployeeSearchCriteria criteria);

IList<Registration> SearchRegistrations(RegistrationSearchCriteria criteria);

bool SaveRegistration(Registration r);

bool GenerateDeepZoomImage(DeepZoomImage img);

bool DeleteRegistration(Registration r);

}

public interface IBusinessDao

{

T GetEntityById<T>(String id) where T : Entity;

IList<Company> SearchCompanies(CompanySearchCriteria criteria);

IList<Employee> SearchEmployees(EmployeeSearchCriteria criteria);

IList<Registration> SearchRegistrations(RegistrationSearchCriteria criteria);

void SaveRegistration(Registration r);

void DeleteRegistration(Registration r);

}

A persistent business object:


[Serializable]

[DataContract]

public class Employee : Entity

{

[DataMember]

public string FirstName { get; set; }

[DataMember]

public string LastName { get; set; }

[DataMember]

public string Email { get; set; }

[DataMember]

public string Phone { get; set; }

[DataMember]

public Company Company { get; set; }

}

The WCF Service interface:


[ServiceContract]

public interface ISLService

{

[OperationContract]

IList<Company> SearchCompanies(CompanySearchCriteria criteria);

[OperationContract]

IList<Employee> SearchEmployees(EmployeeSearchCriteria criteria);

[OperationContract]

IList<Registration> SearchRegistrations(RegistrationSearchCriteria criteria);

}

Silverlight application code calling the service:


protected void SearchCompanies()

{

try

{

SLServiceClient client = new SLServiceClient();

client.SearchCompaniesCompleted += new EventHandler<SearchCompaniesCompletedEventArgs>(SearchCompaniesCompleted);

client.SearchCompaniesAsync(new CompanySearchCriteria() { NameLike = "These Days" });

}

catch

{

// ..

}

}

A sample unit test written against the DAO:


[TestMethod]

public void GetEntitiesById()

{

var mockReg = MockFactory.Instance.CreateMockObject<Registration>();

BusinessDao.Instance.SaveRegistration(mockReg);

var regById = BusinessDao.Instance.GetEntityById<Registration>(mockReg.Id);

Assert.IsNotNull(regById, "Unable to retrieve registration by id");

var employeeById = BusinessDao.Instance.GetEntityById<Employee>(mockReg.Employee.Id);

Assert.IsNotNull(employeeById, "Unable to retrieve employee by id");

var compById = BusinessDao.Instance.GetEntityById<Company>(mockReg.Employee.Company.Id);

Assert.IsNotNull(compById, "Unable to retrieve company by id");

BusinessDao.Instance.DeleteRegistration(mockReg);

}