1

I have an IServiceLocator interface with a method: GetInstance<T>()

When I mock this up (using Moq and NUnit), I want to be able to return mocks in some scenarios, but the real implementation in others.

I'm aware I could write the following statement for every interface I have:

     var factory = new MockRepository(MockBehavior.Loose);
     var serviceLocator = factory.Create<IServiceLocator>();
    var myInterfaceMock = factory.Create<IMyInterface>();
    serviceLocator.Setup(locator => locator.GetInstance<IMyInterface>())
                  .Returns(myInterfaceMock.Object);

and return mocks when for certain interfaces and actual implementations for others, but is there a way of doing it, something like:

 var serviceLocator = factory.Create<IServiceLocator>();
 var myInterfaceMock = factory.Create<IMyInterface>();

 //Real implementation which returns actual implementations of the interfaces
 var realServiceLocator = new ServiceLocator();

//Setup the mock locator to return mocks in some circumstances, and calls to the real service locator in others
     serviceLocator
            .Setup(locator => locator.GetInstance<T>())
            .Callback(() =>
            {
                var type = typeof (T);
                if (type == IMyInterface)
                {
                   return myInterfaceMock;
                }
                else
                {
                   return realServiceLocator.GetInstance<T>();
                }
             });
Ben
  • 3,926
  • 12
  • 54
  • 87
  • 1
    Are you using a dependency injection framework? What object type is factory? I would be helpful to see just a little more code or have more insight into how factory is derived. – Josiah Peters Dec 02 '15 at 16:00
  • Good point Josiah. I've edited the code above to show that the "factory" class is Moq "MockRepository" class. The "ServiceLocator" above is a class that I've created which effectively wraps calls to AutoFacs "AutofacServiceLocator" class. – Ben Dec 02 '15 at 16:35
  • Mocking a service locator doesn't make much sense. It supports your infrastructure but the infrastructure doesn't use it directly. More here http://stackoverflow.com/questions/5761167/mocking-an-ioc-container – Wiktor Zychla Dec 02 '15 at 16:44

0 Answers0