Ordering method return values with Rhino-Mock stubs

后端 未结 2 1454
面向向阳花
面向向阳花 2021-01-04 23:24

I\'ve started experimenting with Rhino-Mocks (3.6) while reading Roy Osherove\'s The Art of Unit Testing. He has an example that demonstrates that a mocked method

2条回答
  •  长情又很酷
    2021-01-05 00:24

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

提交回复
热议问题