使用起订量来验证调用正确的顺序做 [英] Using Moq to verify calls are made in the correct order

查看:194
本文介绍了使用起订量来验证调用正确的顺序做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试下面的方法:

I need to test the following method:

CreateOutput(IWriter writer)
{
    writer.Write(type);
    writer.Write(id);
    writer.Write(sender);

    // many more Write()s...
}

我创建了一个Moq'd IWriter ,我想,以确保写()方法所谓正确的顺序。

I've created a Moq'd IWriter and I want to ensure that the Write() methods are called in the right order.

我有以下的测试code:

I have the following test code:

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

然而,第二次调用write() CreateOutput()(写的 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.".

我也发现很难找到任何明确的,最新的最新文档/起订量序列的例子。

I'm also finding it hard to find any definitive, up-to-date documentation/examples of Moq sequences.

我是不是做错了什么,或者我可以不设置使用相同的方法的顺序?
如果没有,有没有我可以使用其他的(pferably使用起订量/ NUnit的$ P $)?

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.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).

如果您希望只使用起订量,那么你就可以通过验证回调方法调用顺序:

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

这篇关于使用起订量来验证调用正确的顺序做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆