C# Rhino Mocks-设置属性时引发事件
每当使用Rhino Mock设置某个属性时,我想在存根对象上引发一个事件。例如C# Rhino Mocks-设置属性时引发事件,c#,rhino-mocks,C#,Rhino Mocks,每当使用Rhino Mock设置某个属性时,我想在存根对象上引发一个事件。例如 public interface IFoo { int CurrentValue { get; set; } event EventHandler CurrentValueChanged; } 设置CurrentValue将引发CurrentValueChanged事件 我尝试了myStub.Expect(x=>x.CurrentValue)(y=>myStub.Raise…这不起作用,因为属性是可设置
public interface IFoo
{
int CurrentValue { get; set; }
event EventHandler CurrentValueChanged;
}
设置CurrentValue
将引发CurrentValueChanged
事件
我尝试了myStub.Expect(x=>x.CurrentValue)(y=>myStub.Raise…
这不起作用,因为属性是可设置的,并且它说我正在为一个已经定义为使用PropertyBehaviour的属性设置期望值。而且我知道这是一种滥用的行为,我对此并不满意
实现这一点的正确方法是什么?您很可能创建了存根,而不是模拟。唯一的区别是存根默认具有属性行为
因此,完整的实现如下所示:
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);
IFoo mock=MockRepository.GenerateMock();
//自建属性行为的变量
int电流值;
//设置值:
嘲弄
.Stub(x=>CurrentValue=Arg.Is.Anything)
.何时呼叫(呼叫=>
{
currentValue=(int)call.Arguments[0];
myStub.Raise(/*…*/);
})
//从模拟中获取价值
嘲弄
.Stub(x=>CurrentValue)
//Return不起作用,因为需要在运行时指定该值
//它仍然被用来让犀牛开心
.返回(0)
.WhenCall(call=>call.ReturnValue=currentValue);
您很可能创建了存根,而不是模拟。唯一的区别是存根默认具有属性行为
因此,完整的实现如下所示:
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);
IFoo mock=MockRepository.GenerateMock();
//自建属性行为的变量
int电流值;
//设置值:
嘲弄
.Stub(x=>CurrentValue=Arg.Is.Anything)
.何时呼叫(呼叫=>
{
currentValue=(int)call.Arguments[0];
myStub.Raise(/*…*/);
})
//从模拟中获取价值
嘲弄
.Stub(x=>CurrentValue)
//Return不起作用,因为需要在运行时指定该值
//它仍然被用来让犀牛开心
.返回(0)
.WhenCall(call=>call.ReturnValue=currentValue);
我不敢相信要获得一些非常简单的行为需要做多少工作。但令人惊讶的是,你的代码确实有效。谢谢!@RichK:是的,它很复杂。我从来没有做过这样的设置。我想知道你是否真的需要这个,或者你是否滥用模拟框架来重建另一个组件的逻辑。我不敢相信需要做多少工作去做一些非常简单的行为。但令人惊讶的是,你的代码确实有效。谢谢!@RichK:是的,它很复杂。我从来没有做过这样的设置。我想知道你是否真的需要这个,或者你是否滥用模拟框架来重建另一个组件的逻辑。