简体   繁体   English

如何模拟作为接口的接口属性

[英]How do I Mock an interface property that is an interface

public interface IFoo
{
    IFoo2 Foo2 { get; }
}

public interface IFoo2
{
    string FooMethod();
}

Say I have the 2 interfaces above. 说我有上面的2个接口。 I am trying to mock the interface that is set up as a property on the other interface. 我正在尝试模拟在另一个接口上设置为属性的接口。 Is this possible? 这可能吗?

Mock<IFoo> mockFoo = new Mock<IFoo>();
Mock<IFoo2> mockFoo2 = new Mock<IFoo2>();

mockfoo.SetupGet<IFoo2>(x => x.Foo2).Returns(mockFoo2);

Complains that it cant convert a IFoo2 to Moq.Mock<IFoo2> : 抱怨它不能将IFoo2转换为Moq.Mock<IFoo2>

Error CS1503 Argument 1: cannot convert from 'Moq.Mock<IFoo2>' to 'IFoo2' 错误CS1503参数1:无法从'Moq.Mock <IFoo2>'转换为'IFoo2'

Reference the Object property to access the mocked instance. 引用Object属性以访问模拟的实例。

Mock<IFoo> mockFoo = new Mock<IFoo>();
Mock<IFoo2> mockFoo2 = new Mock<IFoo2>();

mockFoo.SetupGet(x => x.Foo2).Returns(mockFoo2.Object);

The reason why it did not work was that you forgot .Object on the inner mock instance when you set up the outer mock (see Grant Winney's answer). 它不起作用的原因是,当您设置外部模拟时,您忘记了内部模拟实例上的.Object (请参阅Grant Winney的答案)。

But note that you do not have to mention the inner mock (your mockFoo2 ) explicitly. 但请注意,你没有提到内部模拟(您mockFoo2 )明确。 You can just pass the outer mock a "long" expression tree with an extra period . 您可以将外部模拟传递给带有额外句点的“长”表达式树. ("auto-mocking hierarchies (also known as recursive mocks )"). (“自动模拟层次结构(也称为递归模拟 )”)。 Like this: 像这样:

Mock<IFoo> mockFoo = new Mock<IFoo>();
mockFoo.Setup(x => x.Foo2.FooMethod()).Returns("your string");

// use 'mockFoo.Object' for your test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM