2011-05-11 76 views
1

我想提出一个存根对象上的事件,只要使用Rhino Mocks设置某个属性。例如。犀牛嘲笑 - 提高事件当属性集

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

设置CurrentValue将提高CurrentValueChanged事件

我试图myStub.Expect(x => x.CurrentValue).WhenCalled(y => myStub.Raise...不工作,因为该属性是可设置的,它说我在已经定义为使用PropertyBehaviour一个属性设置预期。另外我知道这是对WhenCalled的滥用,我并不高兴。

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

回答

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

我不能相信多少工作需要去得到一些非常简单的行为。但令人惊讶的是,你的代码确实有效。谢谢! – RichK 2011-05-11 12:18:08

+0

@RichK:是的,它很复杂。我从来没有必要做这样的设置。我不知道你是否真的需要这个,或者如果你滥用模拟框架来重建另一个组件的逻辑。 – 2011-05-11 12:30:51