I believe this post lacks a summary:
Mock.Of<Object>()
returns the mocked instance of Object
(the "mockee" if you want), while new Mock<Object>()
returns the "mocker".
1. Better readability of Mock.Of<Object>()
esp. for mocking properties.
2. Mock<Object>()
is a lot more flexible. To access the full functionality, though, you need the mocker instead of the mocked instance. Among these features are:
Read-only properties. I want to add: you can mock read-only properties with new Mock<IReadOnlyObject>()
but not with Mock.Of<Object>()
.
Exceptions. Methods throwing exceptions can be done with new Mock<Object>.Setup(m => m.SomeMethod()).Throws<Exception>();
.
Sequences. You can set up sequences of events.
var mock = new Mock<IObject>();
mock.SetupSequence(m => m.GetCount())
.Returns(3) // will be returned on 1st invocation
.Returns(2); // will be returned on 2nd invocation
etc.
Mock.Of<Object>()
can overcome these disadvantages using Mock.Get(Mock.Of<Object>())
. Now you can use Setup
, SetupSequence
, etc. But it's a detour and we lose the advantage of readability.
The other way round, we can directly set properties of the mocked instance with mock.Object
(see below). It will not work with MockBehavior.Strict
, though, while setting the property using Mock.Of<Object>()
will work also work for strict mocks.
var mock = new Mock<IObject>();
mock.Object.SomeProperty = 5;
Feel free to add more insight to this summary