c# - mock一个方法在使用Moq第二次调用时返回一个不同的值



我正在使用Moq模拟存储库与异步方法。这个方法必须被调用2次。在这个方法的第一次调用,我需要得到空值。其次,我需要得到一些参数。如果这个方法不是异步的,那么我可以使用

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

相关内容

  • 没有找到相关文章