繁体   English   中英

犀牛Mo-设置属性时引发事件

[英]Rhino Mocks - Raise Event When Property Set

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

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

设置CurrentValue将引发CurrentValueChanged事件

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

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

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

因此完整的实现如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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