這篇文章幫助我瞭解Mock.Of <牛逼>: Old style imperative Mock<T> vs functional Mock.Of<T>
如在後解釋的,Mock.Of <牛逼>你說「給我一個行爲像這樣的模擬」 (或模擬s。如果您需要獲取許多對象(IEnumerable)),請致電<T>)。它使得模擬的聲明更加簡潔。
實施例用模擬<Ť>(返回一個模擬)使用Mock.Of <Ť>
var el1 = new Mock<IElementInfo>();
el1.Setup(x => x.Id).Returns(Guid.NewGuid());
el1.Setup(x => x.Multiplicity).Returns(Multiplicity.Single);
var c1 = new Mock<ICollectionInfo>();
c1.Setup(x => x.Id).Returns(Guid.NewGuid());
c1.Setup(x => x.Multiplicity).Returns(Multiplicity.Multiple);
var p1 = new Mock<IPropertyInfo>();
p1.Setup(x => x.Id).Returns(Guid.NewGuid());
p1.Setup(x => x.Name).Returns("Foo" + Guid.NewGuid().ToString());
p1.Setup(x => x.Type).Returns("System.String");
var p2 = new Mock<IPropertyInfo>();
p2.Setup(x => x.Id).Returns(Guid.NewGuid());
p2.Setup(x => x.Name).Returns("Bar" + Guid.NewGuid().ToString());
p2.Setup(x => x.Type).Returns("System.String");
var elementInfoMock = new Mock<IElementInfo>();
elementInfoMock.Setup(e => e.Id).Returns(Guid.NewGuid());
elementInfoMock.Setup(e => e.Multiplicity).Returns(Multiplicity.Multiple);
elementInfoMock.Setup(e => e.Elements)
.Returns(new List<IAbstractElementInfo>
{
el1.Object,
c1.Object,
});
elementInfoMock.Setup(x => x.Properties).Returns(
new List<IPropertyInfo>
{
p1.Object,
p2.Object,
});
this.elementInfo = elementInfoMock.Object;
相同例子(返回類的一個實例)
this.elementInfo = Mock.Of<IElementInfo>(x =>
x.Id == Guid.NewGuid() &&
x.Multiplicity == Multiplicity.Multiple &&
x.Elements == new List<IAbstractElementInfo>
{
Mock.Of<IElementInfo>(e => e.Id == Guid.NewGuid() && e.Multiplicity == Multiplicity.Single),
Mock.Of<ICollectionInfo>(e => e.Id == Guid.NewGuid() && e.Multiplicity == Multiplicity.Single),
} &&
x.Properties == new List<IPropertyInfo>
{
Mock.Of<IPropertyInfo>(p => p.Id == Guid.NewGuid() && p.Name == "Foo" + Guid.NewGuid() && p.Type == "System.String"),
Mock.Of<IPropertyInfo>(p => p.Id == Guid.NewGuid() && p.Name == "Foo" + Guid.NewGuid() && p.Type == "System.String"),
});
這裏的答案 - HTTPS ://cmatskas.com/improve-your-unit-tests-with-mock-of/ – niksofteng