2011-05-11 41 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