简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM