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

时间:2016-10-15 11:48:33

标签: c# moq automoq

我正在使用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" });

但是我需要一次调用吗?

1 个答案:

答案 0 :(得分:4)

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

      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" }));