I am trying to make a mock dynamically with a loop that returns values based on a queue. The code used is as follows(Got it from another answer on stackoverflow).
var numberQueue = new Queue<int>(new[] { 4, 8, 16, 43});
var mock = new Mock<ITest>();
mock.SetupSequence(x => x.GetNumber()).Returns(numberQueue.Dequeue);
int x1 = mock.Object.GetNumber(); // expected: 4 actual: 4
int x2 = mock.Object.GetNumber(); // expected: 8 actual: 0
int x3 = mock.Object.GetNumber(); // expected: 16 actual: 0
int x4 = mock.Object.GetNumber(); // expected: 32 actual: 0
x1.Should().Be(4); // passes
x2.Should().Be(8); // fails
x3.Should().Be(16); // fails
x4.Should().Be(32); //fails
The first one works fine but after that everything is 0. I am trying to get it running in this way because I want to be able to dynamically setup a mock for an IDataReader.
CodePudding user response:
There are multiple ways to fix your problem, let me show you the three most basic ones.
Option #1
Use Setup
instead of SetupSequence
mock.Setup(x => x.GetNumber())
.Returns(numberQueue.Dequeue);
After this change your test will fail at the x4.Should().Be(32)
line because x4
is 43.
Option #2
Use SetupSequence
with multiple Returns
calls
mock.SetupSequence(x => x.GetNumber())
.Returns(numberQueue.Dequeue)
.Returns(numberQueue.Dequeue)
.Returns(numberQueue.Dequeue)
.Returns(numberQueue.Dequeue);
Option #3
mock.SetupSequence(x => x.GetNumber())
.Returns(4)
.Returns(8)
.Returns(16)
.Returns(43);