犀牛模拟 - 属性设置时引发事件
本文关键字:事件 设置 模拟 属性 犀牛 | 更新日期: 2023-09-27 17:56:20
每当使用 Rhino Mocks 设置某个属性时,我想在存根对象上引发一个事件。
例如public interface IFoo
{
int CurrentValue { get; set; }
event EventHandler CurrentValueChanged;
}
设置CurrentValue
将引发CurrentValueChanged
事件
我已经尝试了myStub.Expect(x => x.CurrentValue).WhenCalled(y => myStub.Raise...
它不起作用,因为该属性是可设置的,并且它说我正在对已经定义为使用 PropertyBehavior 的属性设置期望。我也知道这是对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);