犀牛嘲笑 - 物业集合时提升事件

时间:2011-05-11 10:57:35

标签: c# rhino-mocks

每当使用Rhino Mocks设置某个属性时,我想在存根对象上引发一个事件。 E.g。

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

设置CurrentValue会引发CurrentValueChanged事件

我已经尝试了myStub.Expect(x => x.CurrentValue).WhenCalled(y => myStub.Raise...这不起作用,因为该属性是可设置的,它说我正在设置对已经定义为使用PropertyBehaviour的属性的期望。我也知道这是对WhenCalled的滥用,我对此并不感到高兴。

实现这一目标的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

你很可能创建了一个存根,而不是模拟。唯一的区别是默认情况下存根具有属性行为。

所以完整的实现如下:

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