Thursday, July 30, 2009

Legend.Fakes configuration fluent interface

As I mentioned in my earlier post one of the things I want to avoid in my mock-/stub-/fake-framework is extension methods that clutter intellisense, this means that you have to get a configuration object to be able to start configuring your fake, don’t be afraid though, it’s really easy and there are two ways to do it. The first is to call the static method “Fake.Configure(object fakedObject)” with the fake object you want to configure, but you can also import the namespace “Legend.Fakes.ExtensionSyntax” and now you can call the “Configure” extension method directly on your faked object. If you do the latter you will have ONE extension method cluttering intellisense, but I can live with just one. Once you have the configuration object you have a fluent interface API.

IPerson person = A.Fake<IPerson>();

// Static method...
Fake.Configure(person);

// Once Legend.Fakes.ExtensionSyntax is imported you can use...
person.Configure();

 

When you have created a fake, the interface of the fake is a lot more discoverable since intellisense shows you what interface it provides: nonCluttered

The fluent interface is context aware so subsequent calls will only have certain options available depending on the call before. For example you can only specify a return value if the call you’re configuring is not a void call:

functionCall

A void call would look like this:

voidCall

Here’s some example configuration code:

var file = A.Fake<IFile>();

file.Configure()
    .CallsTo(x => x.Delete())
    .Throws(new NotSupportedException("You're not allowed to delete a file."))
    .Once();

file.Configure()
    .CallsTo(x => x.GetFileSizeInBytes()).Returns(400);

file.Name = "c:\filename.txt";

No comments:

Post a Comment