Ordering method return values with Rhino-Mock stubs

懵懂的女人 提交于 2019-11-30 19:28:12

The bit you're missing is to tell the stub that the first value should only be returned once:

...
using (mocks.Record())
{
    stub.GetMessageForValue("a");
    LastCall.Return("First call").Repeat.Once();
    stub.GetMessageForValue("a");
    LastCall.Return("Second call");
}

Of course your "Second call" really means "Second-or-subsequent call" unless you impose other restrictions with Repeat.

You might also consider using the newer Arrange, Act, Assert (AAA) syntax RhinoMocks now offers:

[Test]
public void StubMethodWithStringParameter_ScriptTwoResponses_SameResponseReceived()
{
    IMessageProvider stub = MockRepository.GenerateStub<IMessageProvider>();

    stub.Expect(mp => mp.GetMessageForValue("a"))
        .Return("First call")
        .Repeat.Once();
    stub.Expect(mp => mp.GetMessageForValue("a"))
        .Return("Second call");

    Assert.AreEqual("First call", stub.GetMessageForValue("a"));
    Assert.AreEqual("Second call", stub.GetMessageForValue("a"));
}

It's a little more concise and generally saves you from having to worry about the record-playback-assert state of the stub. Derick Bailey wrote an article about using Repeat on Los Techies. It also happens to use the AAA syntax).

I think if you are working with stubs, using Expect does not fit as you do not want an expectation but a replacement for your dependency.

So I believe if you use the stub syntax it makes more sense:

stub.Stub.(s=>s.GetMessageForValue("a"))
                            .Return("First call").Repeat.Once(); 

stub.Stub.(s=>s.GetMessageForValue("a"))
                            .Return("Second call").Repeat.Any;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!