【问题标题】:C# – Mocking a method to return a different value when called a second time using MoqC# – 使用 Moq 在第二次调用时模拟方法以返回不同的值
【发布时间】:2016-10-15 11:48:32
【问题描述】:

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

但我需要一次调用它?

【问题讨论】:

    标签: c# moq automoq


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多