Today I got a bit stuck whilst running my unit tests. I couldn’t for the life of me figure out why they were failing.
I’m trying to create lots of users, so I mocked the User Service thus:
var createdUsers = CreateUsers(userNames, accountId);
for (int i = 0; i < _users.Length; i++)
{
_mockUserService
.Setup(x => x.Create(It.IsAny()))
.Returns(createdUsers[i]);
}
As you can see I’ve got a for loop which will make sure that each time the service is called it returns a created user.
Unfortunately this doesn’t work. After a bit of googling I found Phil Haack’s blog post on how to properly use Moq to do this.
Turns out that no matter how many times you perform a mock on a service it’s the last one that it uses. Every time. So rather than returning each of my users the mocked object only ever returns the last one in my list. ) :
The way to fix this is to use a queue:
var createdUsers = CreateUsers(userNames, accountId);
for (int i = 0; i < _users.Length; i++)
{
_mockUserService
.Setup(x => x.Create(It.IsAny()))
.Returns(new Queue(createdUsers).Dequeue);
}
Did you get that? Return a new Queue object made up of your IEnumerable list of objects and dequeue it.
Hope this helps someone else.