Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

Building FactoryGirl.NET

factory_girl.jpgAs some of you might have noticed, I’ve been talking about Ruby and Ruby on Rails more recently. It’s often good to get outside your comfort zone and see how other (web) developers live. One of the areas where Ruby really excels is the wealth of innovative testing/spec’ing libraries available. When writing tests/specs, we need objects to play with. Ruby has a variety of options in this regard, but I particularly like the factory approach espoused by gems such as factory_girl or machinist. I’m partial to factory_girl. So let’s take a look at the syntax and see if we can create something similar for .NET. First off, let’s take a look at the usage syntax:

describe Site do
  it "should register a new user" do
    user = FactoryGirl.build(:user)
    site = Site.new
    site.register(user)
    site.users.should include(user)
  end
end

If we want to customize the instance, we can do that too by passing in a hash as the second argument:

describe Site do
  it "should not register new admin users" do
    user = FactoryGirl.build(:user, :admin => true)
    site = Site.new
    site.register(user)
    site.should_not include(user)
  end
end

What is interesting about factory_girl is that we can create instances of objects without the visual clutter of irrelevant properties. A user requires a first and last name, but in the above cases, we don’t care what they are. In the second case, we can see that the user being an admin is important for this test/spec. By removing the irrelevant properties, we can quickly see at a glance the data that matters for this spec. We also have the advantage that as properties are added to the User class, we have one place to update them (e.g. in the factory_girl definition) and we don’t have to wade back through all our tests adding values for required properties.

ASIDE: Now you might be tempted to say that we’ve been doing something like this in .NET with the Object Mother pattern. The Object Mother pattern is a factory of sorts. The problem is that it tends to be a dumping ground for different variations of the test objects. For example, ObjectMother.CreateUser(), ObjectMother.CreateAdminUser(), ObjectMother.CreateUserWithFirstName(string firstName), ObjectMother.CreateAdminUserWithFirstName(string firstName). The result is a tightly-coupled big ball of testing mud where the team is loathe to re-use ObjectMother methods for fear of breaking other tests. So you end up with this sprawling mass of methods for creating test data, which is separated from the tests themselves. Not a good place to be in.

Let’s look at the syntax for defining our factories in factory_girl:

FactoryGirl.define do
  factory :user do
    first_name 'John'
    last_name  'Doe'
    admin      false
  end
end

There is a lot more to factory_girl than I’ve covered above. When defining factories, you can create associations, lazy attributes, aliases, sequences, callbacks, and much more to keep your factories clean, lean, and mean. When using the factories, there is more than just FactoryGirl.build. There is also FactoryGirl.create, which saves the built instance to the database, FactoryGirl.attributes_for, which provides you with a hash of values often useful for testing Controller create actions, and FactoryGirl.build_stubbed, which returns a stubbed out instance. Here we’re going to focus on FactoryGirl.build to see how close we can get to the Ruby syntax, but written in C#.

Let’s start by looking at what our definition syntax could look like in C#.


FactoryGirl.Define(() => new User());

We give FactoryGirl a Func that creates an instance of the object. Note the use of C# type inferencing so that we don’t have to specify the generic method argument on FactoryGirl.Define.


public static class FactoryGirl {
  private static readonly IDictionary<Type, Func> builders = new Dictinonary<Type, Func>();

  public static void Define(Func builder) {
    if(builders.ContainsKey(typeof(T))) throw new DuplicateFactoryException();
    builders.Add(typeof(T), () => builder());
  }
}

Basically I’m just keeping a hash table of Type versus Func. That way when I get asked to build an object later, I can look it up and run the Func. I have to play some games with the C# type system. My hash table has to store Func because the generic parameter is declared on the methods, not the class. C# is also not able to implicitly convert Func to Func. So I have to add a lambda to the hash table that calls the builder rather than adding the builder directly.


builders.Add(typeof(T), builder); // Compiler error

Whereas the following makes the C# compiler happy.


builders.Add(typeof(T), () => builder()); // Compiler is happy

Now let’s look at the API for building an object.


var user = FactoryGirl.Build();

From an implementation standpoint, we simply need to find the appropriate Func and execute it.

public static class FactoryGirl {
  public static T Build() {
    return (T) builders[typeof(T)];
  }
}

Simple enough. Now if we want to customize the object built…


var admin = FactoryGirl.Build(x => x.Admin = true);

We really just need to accept an Action, which we will execute after the object is constructed.

public static class FactoryGirl {
  public static T Build(Action overrides) {
    var result = (T) builders[typeof(T)];
    overrides(result);
    return result;
  }
}

With this simple implementation, we now have a central place to define our factories and build objects. Any customizations required are in the tests/specs themselves making it easier to understand our intentions in the tests/specs. When we add a new required property, we need to simply update our factory definition with an appropriate default. If needed, you can easily call FactoryGirl.Build() from within a factory definition. I have used this FactoryGirl technique in a production application and it dramatically cleaned up our specification code as compared to a previous project that used Object Mother. I hope it gives you some ideas of how to clean up your own test/spec code. If you are curious about the code or interested in extending FactoryGirl.NET to add some missing capabilities, such as Create, AttributesFor, BuildStubbed, or anything else, you can find the code on GitHub.com here.

UPDATE: A few people have asked me about customizing multiple properties when building an object. FactoryGirl.NET already supports this using the following syntax:

var user = FactoryGirl.Build(x => {
                x.Admin = true;
                x.Age = 42;
           });
Posted in .NET | 16 Comments

JetBrains Newest Technical Evangelist

logo.gifTo say that I’m a big fan of JetBrains is a bit of an understatement. I’m always talking about ReSharper, dotTrace, dotCover, dotPeek, TeamCity, and many other JetBrains products in person, on Twitter, on my blog, in talks, … Many years ago I released a (now-defunct) ReSharper test runner plug-in. (Defunct because the functionality is now included in ReSharper itself.) I’m one of a team of people running http://teamcity.codebetter.com, which is a widely-used OSS build server run by CodeBetter.com and Devlicious.com in collaboration with JetBrains. I’m on the board of the JetBrains Development Academy. I was JetBrains booth babe/demo monkey at PDC a few years back. I authored the ReSharper course for Pluralsight. (N.B. Through a cross-promotion deal, JetBrains includes one-month access to my Pluralsight ReSharper course for new and existing ReSharper users.) I’m sure there are things that I’m forgetting.

Recently JetBrains approached me about joining their team as a technical evangelist. I was flattered and honoured at being considered for such a position. Then came the hard questions…

Me: I don’t want to be pushing products for the sake of products.

JB: We don’t want you to. We want you to evangelize software best practices and talk about where JetBrains products make developers’ lives easier.

Me: My interests extend beyond .NET. I’ve also done a lot of JavaScript and web work. Plus I’ve been getting into Ruby and Ruby on Rails a lot recently. And I’d like to do some iOS development.

JB: That sounds great! As you know we’ve got products in all those areas and can use someone with that kind of breadth.

Me: I don’t want to put Hadi out of a job.

JB: No worries. You’ll be Hadi’s counterpart in North America. We’ve got enough to keep both of you busy for a long time.

So Hadi and I will be working closely with the rest of the JetBrains team to bring you more awesomeness from JetBrains. More awesome blog posts. More awesome screencasts. More awesome presentations. And of course more awesome information about JetBrains products. (Let’s be realistic. We’ve all got mortgages/expenses to pay.) If you have questions, comments, or quibbles about JetBrains products – especially how we can make them better – Hadi and I are the people you want to talk to. And we want to talk to you, our community.

Canadian Maple LeafTo answer a few burning questions that I’m sure people have… I’ll still be based out of Calgary, Alberta, Canada. I’ll still be speaking at various conferences and user groups – and not just about JetBrains products. (It will be the usual mix of software practices, development techniques, and technologies. So expect to see me at conferences and events both as a speaker and representing JetBrains.) I’ll still be producing Pluralsight videos. (NHibernate Fundamentals will be available soon and I’m already work on Git Fundamentals. JetBrains and Pluralsight will continue to partner on various initiatives.) I’ll still be involved in open-source software. And I’ll still be causing the usual amount of trouble on Twitter and elsewhere. Happy coding!

Posted in Announcements | 9 Comments

TDD/BDD as Architectural Tools

InfoQ has made another of my DevTeach talks available online – TDD/BDD as Architectural Tools. Enjoy!

TDD/BDD as Architectural Tools

As architects, we have all experienced the folly of BDUF (Big Design Up Front) – spending weeks or months perfecting an architecture that fails when it meets the real requirements and real code. Is it possible to design in the small? How can we avoid unintended complexity, which cripples so many code bases? Can we build enough of an architecture to start writing code and then flesh out our architecture as the code evolves? In this session we examine how Test-Driven Development (TDD) and Behaviour-Driven Development (BDD) allow us to solve these conundrums. We will see how we can use TDD/BDD to focus our architectural efforts in the high-value areas of our code base to achieve just-in-time architecture.

Posted in Agile, Presentations | 2 Comments

Convention-over-Configuration in an Agile World

A friend just pointed out that my presentation on “Convention-over-Configuration in an Agile World” is being featured by InfoQ. (The speaker is always the last to know.) I’m honoured and humbled by the great responses from folks. Worst criticism so far is that the presentation isn’t about TDD/BDD. Well, it’s not. Here is my original description:

Convention-over-Configuration in an Agile World

As developers, we spend an inordinate amount of time writing “glue code”. We write code to transform database rows to domain objects… domain objects to view-models or DTOs… We write code to configure inversion of control containers and wire dependencies together. We write code to style our UIs and respond to UI events. Wouldn’t it be nice if this could happen automagically for us? This session will look at using convention-based approaches using Fluent NHibernate and Castle Windsor to reduce the amount of repetitive code and accelerate application development.

So check it out and let me know what you think…

Posted in Agile, Presentations | 1 Comment

Token Replacement in PowerShell

A question I often get asked is why psake does not include something similar to NAnt’s <replacetokens>. The reason is because it’s so darn easy to do it in PowerShell. Given foo.txt.template:

@@foo@@ is @@bar@@!!!

The following script will perform the replacement:

# replace.tokens.ps1
$foo = 'PowerShell'
$bar = 'da bomb'
(cat foo.txt.template) -replace '@@foo@@', "$foo" `
                       -replace '@@bar@@', "$bar" `
                       > foo.txt

(Note the backticks (`) at the end of the line to denote continuation.)

This script will produce:

PowerShell is da bomb!!!

You could easily write a function that would take care of the nitty gritty details. The @@var@@ is arbitrary. You could use any sequence you like. You can even perform regex matches in the @@var@@ expression if needed. Note the double quotes around “$foo”. This is PowerShell for performing variable replacements in strings. So “$foo” results in the word PowerShell whereas ‘$foo’ results in the word $foo.

So there you have it. Token replacement built right into PowerShell. Happy Scripting!

Posted in PowerShell | 2 Comments