As part of a test, I wish to mock a Get() method using Moq such that it returns a popped value from a Stack every time it’s called.
Unfortunately, Moq’s Setup() methods are only run once and thus, each Get() within my test returns the same top value from the stack on every call.
My test kicks off a process in which multiple Get() methods are called. How would I mock this Get() method such that it pops a new value every time of off a orderedGetOutputs stack?
How about this:
public interface ISomeInterface
{
public string SomeValue { get; set; }
}
[Fact]
public void PropertyReturnsDifferentValueOnEachCall()
{
var stack = new Stack<string>();
stack.Push("World");
stack.Push("Hello");
var mock = new Mock<ISomeInterface>();
mock.SetupGet(s => s.SomeValue).Returns(() => stack.Pop());
// Because the method signature of stack.Pop() matches
// the expectation of Returns(), you could also write
// mock.SetupGet(s => s.SomeValue).Returns(stack.Pop);
var instance = mock.Object;
var resultOne = instance.SomeValue;
var resultTwo = instance.SomeValue;
Assert.NotEqual(resultOne, resultTwo);
}
When mocking a normal method you use .Setup()
, but when you mock a property getter you have to use .SetupGet()
. Regardless of what you mock, the .Returns()
overload takes also a matching Func<>
that can do whatever needed.