Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 207
Martín Caballero Avatar asked Oct 24 '22 22:10

Martín Caballero


1 Answers

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.

like image 108
Alexei Levenkov Avatar answered Nov 08 '22 22:11

Alexei Levenkov