2016-11-17 15 views
0

代碼被嘲笑看起來是這樣的:如何設置moq模擬來引發界面實現中定義的事件,而不是界面本身?

class Foo : IBar 
{ 
    public virtual event EventHandler FooEventHandler; 

    void FooMethod() 
    { 
     // blah, blah, blah... 
    } 

    void IBar.BarMethod() 
    { 
     this.FooEventHandler?.Invoke(this, new EventArgs()); 
    } 
} 

interface IBar 
{ 
    void BarMethod(); 
} 

我想嘲笑富及其實施伊巴爾的,這樣我可以測試它交給主題和斷言。要求告訴我,我不允許將事件處理程序放在IBar界面上,所以the explanation behind this link似乎不適用於我。

回答

0

因爲我與Mock.As<T>()方法處理來引用相同的對象,因爲我知道我需要.As<T>入從富來設置顯式實現IBar.BarMethod()但的IBAR上下文2個不同接口,那麼我需要保持IBAR上下文的設置,同時訪問Foo.FooEventHandler傳遞給.Raises(Action<T> eventExpression, EventArgs args)。所以,我從IBar將我的方式向.As<T>方向下調到Foo環境,從而將Foo.FooEventHandler變成Action<IBar>

[TestMethod] 
public void FooEventRaisedByIBarImplementation() 
{ 
    var foo = new Mock<Foo>(); 
    foo.As<IBar>().Setup(bar => bar.BarMethod()) 
      .Raises(bar => bar.As<Foo>().FooEventHandler += null, new EventArgs()); 
}