Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

moq

automoq

i'm using Moq to mock repository with async method. This method must be called 2 times. In first call of this method i need to get null value. In second i need get some parametr. If this method wasn't async then i can use

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

So error in last line. The result must be like this:

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

But i need it in one invokation?

like image 853
Dima Grigoriev Avatar asked Oct 15 '16 11:10

Dima Grigoriev


1 Answers

Thank you, i have resolved this problem

      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" }));
like image 170
Dima Grigoriev Avatar answered Oct 20 '22 21:10

Dima Grigoriev