我有一个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>();
}
});