Moq在2个接口上具有相同的功能

时间:2011-09-06 13:49:30

标签: c# interface moq

鉴于2个接口具有一个共同的功能

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

我们使用moq

创建两个接口的模拟
Mock<I1> menuServiceMock = new Mock<I1>();
menuServiceMock.As<I2>();

问题是当你在I2上调用Foo时

(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 个答案:

答案 0 :(得分: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());