从方法返回对象的Moq

本文关键字:Moq 对象 返回 方法 | 更新日期: 2023-09-27 17:59:57

我有下面的单元测试,我使用MOQ来设置从类返回的对象。然而,当我尝试引用mock时。对象,它引用的是接口类型,而不是我试图返回的类型

var throughFareIdentifer = new ThoroughfareNumberIdentifier();
var throughfareMock = new Mock<ILLUSiteInformation>();
 throughfareMock.Setup(x => x.GetThroughfareNumber("15")).Returns(throughFareIdentifer);

var siteInformation = _lluSiteInformation.GetSiteDetails("", "", "", "", "", "", "", "", throughfareMock.Object);

throughfareMock。对象应为ThroughfareNumberIdentifier,而不是IlluSiteInformation。

将不胜感激

感谢

Chris

从方法返回对象的Moq

它正在按照你的指示执行。通过创建new Mock<ILLUSiteInformation>();,你在说"给我一个ILLUSiteInformation类型的Mock"。

当你使用你的设置:

throughfareMock.Setup(x => x.GetThroughfareNumber("15")).Returns(throughFareIdentifer);

您说的是"当调用GetThroughfareNumber并将数字15作为字符串传递时,返回throughFareIdentifier"。

调用throughfareMock.Object.GetThroughfareNumber(),而不是像那样使用Mock对象

_lluSiteInformation.GetSiteDetails("", "", "", "", "", "", "", "", throughfareMock.Object.GetThroughfareNumber("15");

确保你只使用数字15作为字符串(因为这是你设置的)。如果您想使用任何字符串,请致电

throughfareMock.Setup(x => x.GetThroughfareNumber(It.IsAny<string>)).Returns(throughFareIdentifer);

如果您想使用int

throughfareMock.Setup(x => x.GetThroughfareNumber(It.IsAny<int>)).Returns(throughFareIdentifer);