Moq设置ServiceLocator

时间:2016-02-13 23:22:22

标签: c# .net moq

我试图为单元测试设置服务定位器,如下所示:

var mockS = new Mock<IServiceLocator>();
ServiceLocator.SetLocatorProvider(() => mockS.Object);
mockS.Setup(x => x.GetInstance<IObjectFactoryMethod<IAddress>>()).Returns(new Mock<ObjectsFactory>().Object);

var factoryMock = new Mock<IObjectFactoryMethod<IAddress>>(MockBehavior.Strict);
factoryMock.Setup(x => x.Create(null)).Returns(new Mock<IAddress>());

var factory = ServiceLocator.Current.GetInstance<IObjectFactoryMethod<IAddress>>();

// testing - factory returns null
var address = factory.Create(null); // address is null

代码执行正常。 factory在调试期间显示为模拟工厂,但是当调用Create(null)时,它返回null而不是new IAddress mock。

1 个答案:

答案 0 :(得分:4)

尝试这样的事情:

var mockS = new Mock<IServiceLocator>();
ServiceLocator.SetLocatorProvider(() => mockS.Object);

var factoryMock = new Mock<IObjectFactoryMethod<IAddress>>(MockBehavior.Strict);
factoryMock.Setup(x => x.Create(null)).Returns(new Mock<IAddress>().Object);

mockS.Setup(x => x.GetInstance<IObjectFactoryMethod<IAddress>>()).Returns(factoryMock.Object);

var factory = ServiceLocator.Current.GetInstance<IObjectFactoryMethod<IAddress>>();

// testing - factory returns null
var address = factory.Create(null); // address is null