I'm currently confuse on how to mock.
I'm using Moq. To mock objects I usually write this way
var mockIRepo = new Mock<IRepo>();
However, I need to create mock object for my setup.
Option1 Is it better to mock my object which only contain properties this way?
var object = Mock.Of<Object>()
Option2 Or this way
var object = new Mock<Object>()
I've read that option 2 has setupproperties which is kinda questionable to me because I could also set the properties in option 1.
Then what is the difference? Or is there a better way?
This post helped me to understand Mock.Of<T> : Old style imperative Mock<T> vs functional Mock.Of<T>
As explained in the post, with Mock.Of<T> you're saying "Give me a mock that behaves like this" (or Mocks.Of<T> if you need to get many objects (IEnumerable)). It makes the declaration of a mock more concise.
Example with Mock<T> (returns a Mock)
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;
Same example using Mock.Of<T> (returns an instance of the class)
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"),
});