Injecting Mocks via IOC (NInject and Rhino Mocks)

Translated from French. Read the original

Here is one of my posts (code developed with Lionel Molas) on a programming website run together with friends: http://www.homonerdicus.com/
The link to the article is this one: http://www.homonerdicus.com/?p=17
Be aware that this post is aimed at people who already know what IOC and mocking are 🙂
Enjoy the read!

Here is a copy of it:
Hello everyone,
Here is a short post explaining the almost seamless integration of Rhino Mocks with NInject. As a reminder, NInject is an IOC framework, and therefore a dependency injection framework. It injects classes and thus allows strong decoupling in your application. Rhino Mocks, on the other hand, is a framework closely tied to testing. During a unit test, it lets you “stub out” the dependencies of the component under test in order to isolate it and therefore guarantee that it can truly be tested as a “unit”.
The goal of this article is to design a loosely coupled application with NInject that is easy to “mock” with RhinoMock. To follow this article, you should be familiar with the concepts of mocking and injection, and with how to use Rhino Mocks.

Context

In our test project, NInject is installed on the server side. It wires the various classes together while guaranteeing strong decoupling. Then comes the unit testing part. We decide to use Rhino Mocks to make our tests truly “unit” tests. The only problem: dependencies are injected at runtime. So we have to ask NInject to inject Rhino Mocks objects.
The versions used are Rhino Mocks 3.6 and NInject 2.0
Learning by example:
Example of a business class injected with NInject:

public class FileDAO : IFileDAO
 {
     [Inject]
     private IFileDAL _fileDAL { get; set; }
     public virtual File AddFile(string name, FileType fileType, byte[] contentFile)
     {
         //Some stuff here that use _fileDAL
     }
     public virtual bool DeleteFile(long index)
     {
         //Some stuff here that use _fileDAL
     }
 }

In the code above, we can see that the _fileDAL variable is injected by NInject (as shown by the [Inject] tag) when an instance of the class is created.

public void AuthenticateTest()
{
    //Creation of the mock
    IUserDAO = _userDAOMock = Repository.StrictMock()
    //Usefull data for test
    string login = "toto@toto.com";
    string password = "titi";
    Employee user = new Employee(login, password);
    //Record what will be called and what will be returned
    using (NInjectMockProvider.Repository.Record())
    {
        Expect.Call(_userDAOMock.GetEmployee(login, password)).Return(user);
    }
    //Start the "playback" feature.
    using (NInjectMockProvider.Repository.Playback())
    {
        bool authOK = loginService.Authenticate(login, password);
        //Verify that everithing has been properly called
        _userDAOMock.VerifyAllExpectations();
        //Check if the test is OK
        Assert.IsTrue(authOK);
    }
}

In the code above, we can see the few essential steps of using Rhino Mocks:

  • Setting up the test data
  • Recording the mock’s behavior
  • Running the test sequence
  • Checking that what was recorded matches the behavior actually called, and checking the results.

The goal of this article is therefore to get rid of this line:

IUserDAO _userDAOMock = Repository.StrictMock<IUserDAO>();

Since we also use injection in the classes under test, we need to have NInject inject the mocks.

Don’t fight NInject !

To configure injection, NInject relies on a class derived from the abstract NinjectModule class, where you simply override the Load() method to define the bindings in this form:

Bind<IUserDAO>().To<UserDAO>().InSingletonScope();

Ninject lets us add a “Provider” that supplies the instance of the class. The ideal usage in our case would be:

Bind<IUserDAO>().ToProvider<NInjectMockProvider<IUserDAO>>();

We then tell NInject to inject a mock for IUserDAO. In other words, we merge the NInject provider with the Rhino Mocks factory!
What does this provider do?

public class NInjectMockProvider<T> : IProvider where T : class
{
    //References to the MockRepository
    public static MockRepository Repository = new MockRepository();
    //Static dictionnary that allow to create a Mock by kernel
    private static Dictionary<int, object> allItems = new Dictionary<int, object>();
    public object Create(IContext context)
    {
        return CreateInstance(context);
    }
    //Say Ninject what type we are injecting
    public Type Type
    {
        get { return typeof(T); }
    }
    //Create the mock or return the mock already created
    private T CreateInstance(IContext context)
    {
        int temp = context.Kernel.GetHashCode();
        if (!allItems.Keys.Contains(temp))
        {
            allItems.Add(temp, Repository.StrictMock<T>());
    }
    return allItems[temp] as T;
}

Key takeaways about this provider-factory:

  • It is configured for Singleton injection by design. We did not dig any further, as this covered our needs
  • It simulates, from NInject’s point of view, the injection of an abstract class
  • It takes care of creating the typed mocks.

We could improve it by handling the injection scopes (singleton, per thread, “OnePerRequest”), for example.

References:

Ninject Dojo
Rhino Mocks documentation

Special Thanks to:

Lionel Molas, for the pair programming that led us to the solution, and for his idea of publishing it!

All articles