Search code examples
c#rhino-mocksstub

Stub the behavior of a readOnly property


public interface 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.


Solution

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