mercredi 2 décembre 2015

Moq - Return mock based on input

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 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>();
                }
             });

Aucun commentaire:

Enregistrer un commentaire