gpt4 book ai didi

c# - Moq 设置 ServiceLocator

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:25 24 4
gpt4 key购买 nike

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

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

代码执行良好。工厂在调试期间显示为模拟工厂,但是当调用 Create(null) 时,它返回 null 而不是新的 IAddress 模拟。

最佳答案

尝试这样的事情:

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

关于c# - Moq 设置 ServiceLocator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com