模拟属性上的方法



我需要为属性返回的方法设置返回值,基本上我需要设置它的作用:

mockedObject.TheProperty.GetTheValues()

我只需要它返回Enumerable.Empty<MyType>.

为了证明该功能存在,假设

public interface IFoo {
    IBar TheProperty { get; set; }
}
public interface IBar {
    IEnumerable<MyType> GetTheValues();
}
public class MyType { }

Moq 允许自动模拟层次结构,也称为递归模拟

[TestClass]
public class RecursiveMocksTests {
    [TestMethod]
    public void Foo_Should_Recursive_Mock() {
        //Arrange
        IEnumerable<MyType> expected = Enumerable.Empty<MyType>();
        var mock = new Mock<IFoo>();
        // auto-mocking hierarchies (a.k.a. recursive mocks)
        mock.Setup(_ => _.TheProperty.GetTheValues()).Returns(expected);
        var mockedObject = mock.Object;
        //Act
        IEnumerable<MyType> actual = mockedObject.TheProperty.GetTheValues();
        //Assert
        actual.Should().BeEquivalentTo(expected);
    }
}

请注意,从未IBar初始化或配置过。由于上面显示的设置,框架将自动模拟该接口。

但是,如果IBar需要更多功能,则应进行适当的模拟并相应地进行配置。也没有什么可以阻止通过IFoo模拟配置多个IBar成员。

参考最小起订量快速入门:属性

想象一下你有这个:

public interface IA
{
    IEnumerable<MyType> TheProperty { get; set; }
}
public class MyType {}

然后这里是如何模拟它,以便在调用TheProperty时,它返回并IEnumerable.Empty<MyType>

[TestMethod]
public void SomeTest()
{
    /* Arrange */
    var iAMock = new Mock<IA>();
    iAMock.Setup(x => x.TheProperty).Returns(Enumerable.Empty<MyType>());
    /* Act */
    /* Assert */
}

最新更新