Moq 从方法返回对象

Moq returning an object from a method

我有以下单元测试,我正在使用 MOQ 来设置一个对象 returned 来自 class。但是,当我尝试引用 mock.Object 时,它引用的是接口类型,而不是我尝试引用的类型 return

var throughFareIdentifer = new ThoroughfareNumberIdentifier();

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


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

throughfareMock.Object 应该是 ThroughfareNumberIdentifier 而不是 IlluSiteInformation。

如有任何帮助,我们将不胜感激

谢谢

克里斯

它正在按照您的指示进行操作。通过创建 new Mock<ILLUSiteInformation>();,您等于 "Give me a Mock of type ILLUSiteInformation"。

当您使用您的设置时:

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

你说的是 "When GetThroughfareNumber is called, and passed the number 15 as a string, return throughFareIdentifier"。

调用 throughfareMock.Object.GetThroughfareNumber() 而不是像这样使用模拟对象

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