依次验证

时间:2018-08-06 04:57:08

标签: c# unit-testing moq

我正在尝试依次验证一组方法调用。

这是我想做的事的一个样本。该测试应该失败,但实际上可以通过:

sh -c

这应该会失败,因为 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); } } 调用期望使用不同顺序的参数。

我已经这样尝试过Verify

MockSequence

但是我想我做错了。

使用 [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)); } 似乎也不起作用:

MockBehaviour.Strict

我不能使用 [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)); } 来配置传递给模拟调用的参数,因为这些值不是来自可模拟的源。

1 个答案:

答案 0 :(得分:2)

使用MockBehavior.Strict创建模拟

var mock = new Mock<IMyInterface>(MockBehavior.Strict);

将允许您验证呼叫是否按顺序进行。 完整的方法看起来像

[TestMethod]
public void MyTestMethod()
{
    var mock = new Mock<IMyInterface>(MockBehavior.Strict);

    //will fail
    var listOfThings = new List<int> { 5, 4, 3, 2, 1 };

    //will pass
    var listOfOtherThings = new List<int> { 1, 2, 3, 4, 5 };

    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));
}