繁体   English   中英

C# - 当使用Moq第二次调用时,模拟一个返回不同值的方法

[英]C# – Mocking a method to return a different value when called a second time using Moq

我正在使用Moq使用异步方法模拟存储库。 必须调用此方法2次。 在第一次调用此方法时,我需要获取null值。 在第二个我需要得到一些参数。 如果这个方法不是异步,那么我可以使用

 autoMockContext
            .Mock<IPopulationReadRepository>()
            .SetupSequence(method => method.GetCityForNewClients(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
            .Returns(null)
            .Returns(new Population { Id = 100, CityLongName = "Kharkiv, Kharkivska, Slobozhanshina" });

所以最后一行的错误。 结果必须是这样的:

 autoMockContext
            .Mock<IPopulationReadRepository>()
            .Setup(method => method.GetCityForNewClients(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
            .Returns(null);

 autoMockContext
            .Mock<IPopulationReadRepository>()
            .Setup(method => method.GetCityForNewClients(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
            .ReturnsAsync(new Entities.Zonning.Population { Id = 100, CityLongName = "Kharkiv, Kharkivska, Slobozhanshina" });

但我需要一次调用吗?

谢谢,我已经解决了这个问题

      autoMockContext
            .Mock<IPopulationReadRepository>()
            .SetupSequence(method => method.GetCityForNewClients(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
            .Returns(Task.FromResult<Entities.Zonning.Population>(null))
            .Returns(Task.FromResult(new Entities.Zonning.Population { Id = 100, CityLongName = "Kharkiv, Kharkivska, Slobozhanshina" }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM