typemock

Using TypeMock to mock nHibernate's ISession.Load<T>

The development team I work with uses nHibernate for our data-access and data persistence needs. We also use Typemock Isolator to mock classes and methods during unit tests. This is especially handy to mock certain nHibernate API calls to make sure our unit tests are more isolated. Today, I needed a way to mock nHibernate's ISession.Load() for all data objects in the project that use nHibernate. To mock a generic method (like ISession.Load()) I would normally do the following:

Mock<ISession> mock = MockManager.MockObject<ISession>(Constructor.Mocked);
mock.AlwaysReturn("Load", new DynamicReturnValue((parameters, context) =>
{
   // assume MyClass has a constructor with int Id parameter
   return new MyClass( (int)parameters[0] );
}), typeof(MyClass));

That means anytime I call ISession.Load(1);, I get back a new MyClass object with 1 passed into the constructor. But what if I have 50 different classes similar to MyClass that I want to mock like this? The simplest way is to iterate over a list of types needed and mock them as well, like below:

Mock<ISession> mockSession = MockManager.MockObject<ISession>(Constructor.Mocked);
 
// Retrieve all the types in the same assembly as MyClass
// and mock those types that have the "Id" property
Assembly assembly = Assembly.GetAssembly(typeof(MyClass));
foreach (Type type in assembly.GetTypes())
{
   Type objType = type; // this line is needed because 'type' will cause 
                        // issues with the anonymous method below.
 
   if (objType.GetProperty("Id") != null)
   {
      mockSession.AlwaysReturn("Load", new DynamicReturnValue((parameters, context) =>
      {
         return Activator.CreateInstance(objType, parameters[0]);
      }), objType);
   }
}

Obviously you can change the foreach loop to use whatever list of types you need, but this certainly beats having to duplicate code!

Syndicate content