Sohan's Blog

Living the Developer's Life

A Solution to the Problem With Creating Mocks for Interfaces With Generic Methods With NMock

I was so happy with NMock to see how it can dynamically generate mocks of interfaces and also gives me a fluent interface to write expectations and everything it does to help me in unit testing!

However, I could not generate dynamic mocks for interfaces with Generic methods and it kept showing me the ‘TypeLoadException’ on and on. My interface looks like the following -

interface IObjectFactory
{
T GetObject(string id);
}

As I failed to create a mock implementation of this interface using NMock, I just wrote a mock implementation myself, which looks like the following

class MockObjectFactory: IObjectFactory
{
public Type RequestedObjectType;
public string RequestedObjectId;
public T GetObject(string id)
{
RequestedObjectType = typeof(T);
RequestedObjectId = id;
return new Mockery().NewMock();
}
}


And in my test code, just injected the above mock implementation of the IObjectFactory where needed. So, although NMock cannot handle mocking of this type of an interface now, you can actually create a mock implementation and use NMock inside the implementation to help you.