Tidy and clean code

Writing custom assertion handlers for Fluent Tests

leave a comment »

With Fluent Tests you can write tests in your own domain language using custom assertions handlers.

As an example, say you have a class Company and this class has a reference to another class Address, seems like a not so very uncommon scenario. In your unit tests you might want to assert that the company has an address. In a normal scenario this would be done like this :


Well it’s readable, you can se that an assert is made and the address of the company should be set to an instance of a object. If this is done on several occasions you might want to consider using Fluent Tests.

With Fluent Tests you write a custom assertion handler that really just is an extension method. The extension method will be applied to a verb within the Fluent Tests framework.

First off, lets define so classes from the domain, Company and Address.


    public class Company
public string Name { get; set; }
public Address Address { get; set
; }

    public class Address
public string StreetName { get; set; }
public string PostalCode { get; set
; }
public string ZipCode { get; set
; }

The actual assertion handler is written as an extension method for the verb Has. In this case we won’t compare the value against another value so the only parameter in our extension method will be the verb.

    public static class CustomAssertionHandler
public static void Address(this Has<Company
> verb)
                                           "Company has no address");

In our extension method we are using a helper class from the framework, VerbAssert. This class makes it easy to write the actual implementation by using a lambda expression as the actual assert method. When the lambda expression c=>c.Address==null is true, an assertion should be made. If an assertion should be made, an AssertionException will be thrown with the message “Company has no address”.

Now we can use our new assertion handler by simply typing Ensure.That(company).Has.Address();. You are now writing tests in your own domain language!

public class CustomAssertionHandlerTest
public void
var company = new Company

Written by arvander

May 3, 2011 at 5:42 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: