Moq - 根据输入返回模拟

时间:2015-12-02 15:34:07

标签: c# unit-testing moq

我有一个IServiceLocator接口,其中包含一个方法:GetInstance<T>()

当我模拟它时(使用Moq和NUnit),我希望能够在某些情况下返回模拟,但在其他情况下是真实的实现。

我知道我可以为每个接口编写以下语句:

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

并且当某些接口和其他人的实际实现时返回模拟,但有没有办法实现它,如:

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

0 个答案:

没有答案