Mock.Of<Object> VS Mock<Object>()

C#Unit TestingTestingMockingMoq

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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"),
});

Solution 2 - C#

Based on the answers above, I guess when you mostly want to mock properties, Mock.Of<T>() is easier, whereas when you want to mock methods etc., Mock<T> is easier.

  • Mostly mocking properties:
var foo = Mock.Of<Foo>();
foo.Property1 = 1;
foo.Property2 = 2;
foo.Property3 = 3;
  • Mostly mocking methods:
var barMock = new Mock<Bar>();
barMock.Setup(bar => bar.GetValue1()).Returns(1);
barMock.Setup(bar => bar.GetValue2Async()).ReturnsAsync(2);

Solution 3 - C#

Both do the same but with Mock.Of it's more "natural" code.

Using Mock<T> looks more like this (or with Setup/Return like your code):

var mockService = new Mock<ISomeService>();
mockService.SetupProperty(s => s.IsActive);
mockService.Object.IsActive = true;
mockService.SetupProperty(s =>s.DelayTime);
mockService.Object.DelayTime = 5000;

Using Mock.Of<T> you get directly the instance and you can set the value you want. And you can use Mock.Get() to configure any method:

var mockService = Mock.Of<ISomeService>();
mockService.IsActive = true;
mockService.DelayTime = 5000;
Mock.Get(mockService).Setup(s => s.ExecuteTask()).Returns(true);

They do the same, but for more complex services with a lot of properties and methods, I think Mock.Of<T> is more readable

Solution 4 - C#

The big difference I have noticed is that while Mock.Of<T>(m => m.SomeMethod() == someResult) is, IMHO, easier to use and much more readable, you can't set up methods to throw exceptions like you can using the old syntax - e.g. new Mock<T>.Setup(m => m.SomeMethod()).Throws<Exception>();

So you have to use the old way sometimes.

NOTE - If I am mistaken in this, please correct me, but I was not able to find anything on how to do this with the Mock.Of<T> syntax. To be fair, I only searched for about 10m, but...yeah.

Solution 5 - C#

While the newer Mock.Of looks better and requires less coding, it does have limitations (as others have already pointed out).

However, it is indeed possible to do it via Mock.Get().

For example, consider trying to get a mock with default values mocked, however there is no DefaultValue = DefaultValue.Mock on Mock.Of(), so in this case the following can be done:

var obj = Mock.Of<MyType>(t => SomeProp == Mock.Of<PropType>());

// We want SomeProp all sub properties to return mocks
Mock.Get(obj.SomeProp).DefaultValue = DefaultValue.Mock;

// Note that the following step wouldn't be required when using new Mock{DefaultValue = DefaultValue.Mock}
Mock.Get(obj.SomeProp).SetupAllProperties();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchoopauView Question on Stackoverflow
Solution 1 - C#Ricardo stands with UkraineView Answer on Stackoverflow
Solution 2 - C#Shimmy WeitzhandlerView Answer on Stackoverflow
Solution 3 - C#Isaac OjedaView Answer on Stackoverflow
Solution 4 - C#Mike LouxView Answer on Stackoverflow
Solution 5 - C#yoel halbView Answer on Stackoverflow