使用 Moq 验证调用的顺序是否正确 [英] Using Moq to verify calls are made in the correct order
问题描述
我需要测试以下方法:
CreateOutput(IWriter writer)
{
writer.Write(type);
writer.Write(id);
writer.Write(sender);
// many more Write()s...
}
我已经创建了一个 Moq'd IWriter
并且我想确保以正确的顺序调用 Write()
方法.
I've created a Moq'd IWriter
and I want to ensure that the Write()
methods are called in the right order.
我有以下测试代码:
var mockWriter = new Mock<IWriter>(MockBehavior.Strict);
var sequence = new MockSequence();
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedType));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedId));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedSender));
然而,第二次调用 CreateOutput()
中的 Write()
(写入 id
值)会抛出一个 MockException
带有消息IWriter.Write() 调用失败,模拟行为严格.模拟上的所有调用都必须有相应的设置.".
However, the second call to Write()
in CreateOutput()
(to write the id
value) throws a MockException
with the message "IWriter.Write() invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.".
我还发现很难找到任何明确的、最新的 Moq 序列文档/示例.
I'm also finding it hard to find any definitive, up-to-date documentation/examples of Moq sequences.
我做错了什么,或者我不能使用相同的方法设置序列?如果没有,有没有我可以使用的替代方法(最好使用 Moq/NUnit)?
Am I doing something wrong, or can I not set up a sequence using the same method? If not, is there an alternative I can use (preferably using Moq/NUnit)?
推荐答案
在同一个模拟中使用 MockSequence.它肯定会在 Moq 库的后续版本中修复(您也可以通过更改 Moq.MethodCall.Matches
实现来手动修复它).
There is bug when using MockSequence on same mock. It definitely will be fixed in later releases of Moq library (you can also fix it manually by changing Moq.MethodCall.Matches
implementation).
如果您只想使用 Moq,那么您可以通过回调验证方法调用顺序:
If you want to use Moq only, then you can verify method call order via callbacks:
int callOrder = 0;
writerMock.Setup(x => x.Write(expectedType)).Callback(() => Assert.That(callOrder++, Is.EqualTo(0)));
writerMock.Setup(x => x.Write(expectedId)).Callback(() => Assert.That(callOrder++, Is.EqualTo(1)));
writerMock.Setup(x => x.Write(expectedSender)).Callback(() => Assert.That(callOrder++, Is.EqualTo(2)));
这篇关于使用 Moq 验证调用的顺序是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!