Spending my days writing lots of unit tests lately...You know the drill. For most of my tests, I like to use Moq, the .NET mocking library that allows you to mock objects and services. It's one of the best libraries for complementing and supporting unit tests.
So today, I came across the Mock.Of<T>()
. When creating a mock, we tend to use the following syntax:
var mockService = new Mock<ISomeService>();
And then we setup the mock with the appropriate property values and methods in order to use it in our unit tests. So, in this case, we would be doing something like this:
mockService.SetupProperty(s => s.IsActive);
mockService.Object.IsActive = true;
mockService.SetupProperty(s =>s.DelayTime);
mockService.Object.DelayTime = 5000;
// pass the service to your unittest
var anotherService = new AnotherService(mockService.Object);
However, there is a much easier way to set up a mock without all this fluff. It may seem insignificant for this example, but if you have a complicated service/class with lots of methods and properties, this kind of setup can become tedious and error-prone. And that's where Mock.Of<>()
comes in play. Let's see how we can rewrite the above test mock using the new method:
var mockService = Mock.Of<ISomeService>();
mockService.IsActive = true;
mockService.DelayTime = 5000;
Then, you may ask, how do I setup my methods within that service? Easily, by taking advantage of Mock.Get(). Assuming that you have a method in ISomeService
called ExecuteTask()
, you could use the following syntax to set it up in your mock:
var mockService = Mock.Of<ISomeService>();
mockService.IsActive = true;
mockService.DelayTime = 5000;
Mock.Get(mockService).Setup(s => s.ExecuteTask()).Returns(true);
var anotherService = new AnotherService(mockService.Object);
anotherService.Run();
mockService.verify(m => m.ExecuteTask());
Now, if you want to be even more concise, you can rewrite the above like this:
var mockService = Mock.Of<ISomeService>(x => x.IsActive == true && x.DelayTime == 5000);
Using Mock.Of()
and Mock.Get()
to quickly setup mocks for our unit tests results in more concise and readable code. I definitely find the syntax a lot more readable, and since I'm lazy efficient, I like that I have to write less code in my tests.