I am trying to verify a set of method calls in sequence.
Here is a sample of what I would like to do. This test should fail, but it actually passes:
public interface IMyInterface
{
void Method(int i);
}
public class MyClass : IMyInterface
{
public void Method(int i)
{
}
}
[TestMethod]
public void MyTestMethod()
{
var mock = new Mock<IMyInterface>();
var listOfThings = new List<int> { 5, 4, 3, 2, 1 };
MethodUnderTest(mock.Object, listOfThings);
mock.Verify(m => m.Method(1));
mock.Verify(m => m.Method(2));
mock.Verify(m => m.Method(3));
mock.Verify(m => m.Method(4));
mock.Verify(m => m.Method(5));
}
public void MethodUnderTest(IMyInterface myInterface, List<int> things)
{
foreach (var i in things)
{
myInterface.Method(i);
}
}
This should fail, as the Verify
calls expect a different order of parameters.
I have tried MockSequence
like this:
[TestMethod]
public void MyTestMethod()
{
var mock = new Mock<IMyInterface>();
var listOfThings = new List<int> { 5, 4, 3, 2, 1 };
var s = new MockSequence();
mock.InSequence(s).Setup(m => m.Method(1));
mock.InSequence(s).Setup(m => m.Method(2));
mock.InSequence(s).Setup(m => m.Method(3));
mock.InSequence(s).Setup(m => m.Method(4));
mock.InSequence(s).Setup(m => m.Method(5));
MethodUnderTest(mock.Object, listOfThings);
mock.Verify(m => m.Method(1));
mock.Verify(m => m.Method(2));
mock.Verify(m => m.Method(3));
mock.Verify(m => m.Method(4));
mock.Verify(m => m.Method(5));
}
But I guess I'm doing this wrong.
Using MockBehaviour.Strict
doesn't seem to work either:
[TestMethod]
public void MyTestMethod()
{
var mock = new Mock<IMyInterface>(MockBehavior.Strict);
var listOfThings = new List<int> { 5, 4, 3, 2, 1 };
mock.Setup(m => m.Method(1));
mock.Setup(m => m.Method(2));
mock.Setup(m => m.Method(3));
mock.Setup(m => m.Method(4));
mock.Setup(m => m.Method(5));
MethodUnderTest(mock.Object, listOfThings);
mock.Verify(m => m.Method(1));
mock.Verify(m => m.Method(2));
mock.Verify(m => m.Method(3));
mock.Verify(m => m.Method(4));
mock.Verify(m => m.Method(5));
}
I can't use a Setup
to configure the parameters passed into the mock call, as these values do not come from a mockable source.
MethodUnderTest
callsmyInterface.Method
withthings
in the given order ?listOfThings
declared as5, 4, 3, 2, 1
and expecting beeing used as1, 2, 3, 4, 5
.MethodUnderTest
as there is no relevant logic that one may be interested to verify. 3) Verifying method calls with mocks (and even more a calls sequence) is considered a bad practice. If you are willing, I propose that you edit your code with the real meaning and that I help you to either refactor your test so that it provides a value or to conclude that your test is useless and remove it.