Geeks With Blogs
Liam McLennan

I have written about adding support for specifications to NHibernate’s ISession type. Shortly afterwards Paul Stovell moaned on twitter that no one had demonstrated how to mock ISession. Since my implementation relied upon an extension method (QueryBySpecification) I googled how to mock extension methods – and discovered that you can’t. What I did find was Daniel Cazzulino’s post about converting extension methods to methods that return a Func that exposes your extension method. That way you can replace the Func for your tests. This changed my api from




My new test, with mocking, is

public void MockASpecification()
   var canDriveSpecification = new PeopleOverAgeSpecification(16);
   var queryer = Substitute.For<ISpecificationQueryer>();
   queryer.Query(Arg.Any<PeopleOverAgeSpecification>()).Returns(new List<Person> { new Person() });
   SpecificationExtensions.SpecificationQueryerFactory = s => queryer;
   var allPeopleOfDrivingAge = session.Spec().Query(canDriveSpecification);
   Assert.AreEqual(1, allPeopleOfDrivingAge.Count());

The full code is available on the QueryClasses project on github.

Posted on Sunday, March 20, 2011 10:35 AM | Back to top

Copyright © Liam McLennan | Powered by: