Search code examples
c#rhino-mocks

Rhino Mocks - Raise Event When Property Set


I want to raise an event on a stub object whenever a certain property is set using Rhino Mocks. E.g.

public interface IFoo
{
   int CurrentValue { get; set; }
   event EventHandler CurrentValueChanged;
}

Setting CurrentValue will raise the CurrentValueChanged event

I have tried myStub.Expect(x => x.CurrentValue).WhenCalled(y => myStub.Raise... which doesn't work because the property is settable and it says I'm setting expectations on a property which is already defined to use PropertyBehaviour. Also I am aware that this is an abuse of WhenCalled which I'm none too happy about.

What the correct way of achieving this?


Solution

  • You most probably created a stub, not a mock. The only difference is that the stub has property behavior by default.

    So the full implementation is something like the following:

    IFoo mock = MockRepository.GenerateMock<IFoo>();
    // variable for self-made property behavior
    int currentValue;
    
    // setting the value: 
    mock
      .Stub(x => CurrentValue = Arg<int>.Is.Anything)
      .WhenCalled(call =>
        { 
          currentValue = (int)call.Arguments[0];
          myStub.Raise(/* ...*/);
        })
    
    // getting value from the mock
    mock
      .Stub(x => CurrentValue)
      // Return doesn't work, because you need to specify the value at runtime
      // it is still used to make Rhinos validation happy
      .Return(0)
      .WhenCalled(call => call.ReturnValue = currentValue);