下面介绍如何通过建立断言到每一个方法调用来做到这一点。
// Arrange - Build the necessary assertions into the stubbed method invocations.
var mock = MockRepository.GenerateMock<ISomeService>();
mock.Stub(m => m.Method1()).WhenCalled(inv => mock.AssertWasNotCalled(m => m.Method2()));
mock.Stub(m => m.Method2()).WhenCalled(inv => mock.AssertWasNotCalled(m => m.Method3()));
// Act
myObject.Service = mock;
// Assert - Ensure each expected method was called.
mock.AssertWasCalled(m => m.Method1());
mock.AssertWasCalled(m => m.Method2());
mock.AssertWasCalled(m => m.Method3());
由于这是在中行为运行断言混淆了正常的安排,行为断言模式,我想包括对这些情况下更容易地识别测试失败非常具体的错误消息。
mock.Stub(m => m.Method1()).WhenCalled(inv =>
mock.AssertWasNotCalled(m => m.Method2(), opt =>
opt.Message("Method2 cannot be called before Method1.")));
你也可以实现通过在行为的步骤保存在一个变量每次调用的结果,然后在断言步检查可变状态类似的结果。这更好地保留了arrange-act-assert模式的划分,但它更符合编写和维护的管道代码。
// Arrange - Build the necessary state variables into the stubbed method invocations.
bool wasMethod1Called;
bool wasMethod2Called;
bool wasMethod2CalledBeforeMethod1;
bool wasMethod3CalledBeforeMethod2;
var mock = MockRepository.GenerateMock<ISomeService>();
mock.Stub(m => m.Method1()).WhenCalled(inv =>
{
wasMethod1Called = true;
});
mock.Stub(m => m.Method2()).WhenCalled(inv =>
{
wasMethod2Called = true;
wasMethod2CalledBeforeMethod1 = !wasMethod1Called;
});
mock.Stub(m => m.Method3()).WhenCalled(inv =>
{
wasMethod3CalledBeforeMethod2 = !wasMethod2Called;
});
// Act
myObject.Service = mock;
// Assert - Ensure each expected method was called, and that they were called in the right order.
mock.AssertWasCalled(m => m.Method1());
mock.AssertWasCalled(m => m.Method2());
mock.AssertWasCalled(m => m.Method3());
Assert.That(wasMethod2CalledBeforeMethod1, Is.False, "Method2 cannot be called before Method1.");
Assert.That(wasMethod3CalledBeforeMethod2, Is.False, "Method3 cannot be called before Method2.");
这并非总是如此。有秩序问题的有状态对象的合同,你不能总是避免这些合同。 – sanosdole 2012-06-23 16:02:59
我同意@sanosdole的评论,但在我的情况下,你是发现。我应该测试结果...而不是执行。谢谢! – MoMo 2014-03-20 20:07:45
如果代码已经有时间耦合,它也应该被测试。 – SerG 2017-10-03 10:29:00