2011-09-06 43 views
2

由於有共同起訂量2個接口具有相同的功能

public interface I1 { void Foo(string p);}; 
public interface I2 { void Foo(string p);}; 

一個功能2個接口,我們使用MOQ創建這兩個接口的模擬

Mock<I1> menuServiceMock = new Mock<I1>(); 
menuServiceMock.As<I2>(); 

的問題是,當你調用foo I2

(menuServiceMock.Object as I2).Foo("foo"); // in real code, we have a handle on I2 

你不能用驗證:

menuServiceMock.Verify(x => x.Foo("foo"), Times.Once()); 

...因爲只有對I1 :: Foo的調用才被計數。

我們該如何克服這一點(除了在模擬構造中反轉I1和I2)?

回答

1

我認爲你需要做的是:

Mock<I1> menuServiceMock = new Mock<I1>(); 
var i2Mock = menuServiceMock.As<I2>(); 

// Verifies that I2.Foo was called on the object 
i2Mock.Verify(x => x.Foo("foo"), Times.Once()); 
// Verifies that I1.Foo was called on the object: 
menuServiceMock.Verify(x => x.Foo("foo"), Times.Once()); 
+0

從來沒有注意到的是,「由於」函數返回的東西:) – sthiers

相關問題