Friday, November 4, 2011

Moq - Multiple Calls

I previously had the assumption that Moq allowed for Ordered setups, which was apparently mistaken. This must have been in TypeMock or another tool I looked at in the past.

So, I wanted to do three 'boundary value' calls to my service and return a different value from my repository for each call. Now I could do this as three 'setups' with the fixed paramter values, or three separate setup/execute phases, but I wanted a better way that meets the standard setup/execute/verify testing pattern.

Thanks to this blog I have a nice solution.


_hydrantDbSetMoq.Setup(x => x.GetSingle<Hydrant>(It.IsAny<Expression<Func<Hydrant>>>(), It.IsAny<IEnumerable<string>>(), It.IsAny<bool>())).Returns(
new Queue<Hydrant>(new[] { new Hydrant() { HydrantID = 100 }, new Hydrant() { HydrantID = 0 }, new Hydrant() { HydrantID = 0 } }).Dequeue
);

Hydrant actual1 = service.GetHydrant(100);
Hydrant actual2 = service.GetHydrant(-1);
Hydrant actual3 = service.GetHydrant(int.MaxValue);



And each successive call to getHydrant will return the next value in the queue.

No comments:

Post a Comment