gpt4 book ai didi

c# - 顺序验证

转载 作者:行者123 更新时间:2023-12-05 02:15:31 24 4
gpt4 key购买 nike

我正在尝试按顺序验证一组方法调用。

这是我想做的一个示例。这个测试应该失败,但它实际上通过了:

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

我不能使用 Setup 来配置传递给模拟调用的参数,因为这些值不是来自可模拟的源。

最佳答案

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

关于c# - 顺序验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51700786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com