I have moved my active blog over to tumblr. I've maintained this blog for reference but will be posting to http://www.robustsoftware.co.uk instead. I've pointed my Feedburner feed to tumblr so if you're subscribed already you should already have switched with me.

RhinoMocks IQueryable<T> helper

After reading Lee Brandt's post about how my answer to his question on Stack Overflow helped with testing the logic of his queries I realised that people might find one of my test helper extension methods useful.

I found that in my tests I had to mock out the Query<T> function quite a lot which would look something like this:

    1 protected override void EstablishContext()

    2 {

    3     var projects = new[]

    4                    {

    5                        Build.Project().WithName("AAAAAAA").Create(),

    6                        Build.Project().WithName("CCCCCCC").Create(),

    7                        Build.Project().WithName("BBBBBBB").Create()

    8                    };

    9 

   10     Mock<IUnitOfWork>()

   11         .Stub(x => x.Query<Project>())

   12         .Return(projects.AsQueryable());

   13 }

This was adding quite a lot of noise to my tests. I like to keep my tests as clean as possible to make them easier to scan when you need to review and understand them. Because of this I wanted to simplify the stubbing so there was as little code as possible.

This was made possible by this simple extension method:

    1 public static IMethodOptions<IQueryable<TEntity>> ReturnQueryable<TEntity>

    2     (this IMethodOptions<IQueryable<TEntity>> options, params TEntity[] items)

    3 {

    4     return options.Return(items.AsQueryable());

    5 }

The magic sauce in this is the items parameter. I’ve used the params modifier so that I can provide any number of TEntity objects for the IQueryable function to return.

This tidies the above setup code down to this:

    1 protected override void EstablishContext()

    2 {

    3     Mock<IUnitOfWork>()

    4         .Stub(x => x.Query<Project>())

    5         .ReturnQueryable(

    6             Build.Project().WithName("AAAAAAA").Create(),

    7             Build.Project().WithName("CCCCCCC").Create(),

    8             Build.Project().WithName("BBBBBBB").Create()

    9             );

   10 }

I find this much cleaner and easier to read, hope this helps someone out.

Happy testing!

Related posts: