开发者

Stub the behavior of a readOnly property

public interf开发者_开发技巧ace ICell
        {
            int Value{get;}

            void IncrementValue();
        }

I want to create a stub for this interface in RhinoMocks. I have a read only property and i want to increment his value every time i call the IncrementValue() method. Is this possible? I don't want to create a class new for this stub.


I have similar proposal to Jay, just shorter. Not sure if this have some drawbacks so.

   int count = 0;

    var mock = MockRepository.GenerateStub<ICell>();
    mock.Stub(p => p.Value).WhenCalled(a => a.ReturnValue = count).Return(42);
    mock.Stub(p => p.IncrementValue()).WhenCalled(a => {
        count = (int)count+1; 
    });

Return(42) is put there to say "Value returns something, don't throw" and WhenCalled(a => a.ReturnValue = count) overrides that return vale 42 with current value of the count.


You can give rhino mocks a lambda to run when a function get's called. This lambda can then increment a counter. You can find an example here


I came up with this too:

cell.Stub(c => c.Value).WhenCalled(m => m.ReturnValue = cell.GetArgumentsForCallsMadeOn(c => c.IncrementValue()).Count).Return(0);

Before your help i was confused with the behavior of WhenCalled method... but i think your approach is better than this one

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜