Unit testing can be annoying. Sometimes it feels like setting up a delicate house of cards in just the right way and hoping that nobody opens a window to let a breeze knock the whole thing over.
If you’re using inversion of control (and you should be), its a little easier because you can use Moq or NSubstitute to easily create stubs from your interfaces to pass off to the service you want to test. But, as your application grows, it kinda sucks to type Mock<IMyDependentService>().Object for every single dependency.
Autofac.Extras.Moq.AutoMock
I usually use Autofac for my inversion of control container. It was the first one I’ve tried, and I’ve been happy with it (I’ve used others in the past, and they work just fine – but I guess I’m just used to Autofac). If you want to use Moq for your mocking framework (again, it was the first one I’ve tried so I’ve just stuck with it because I haven’t found any limitations that are dealbreakers for me yet).
Autofac has this nifty nuget package Autofac.Extras.Moq that gives you an AutoMock object. If you have specific dependencies that you need to behave a certain way, you can load them into the AutoMock object. Other dependencies that aren’t relevant to what you’re testing can just be ignored, and AutoMock will generate an empty Mock, returning the default values for all of the properties and methods.
What this means is you can spend less time fussing with the mocks, and more time writing meaningful tests.
I copy/paste this TestBase around to all of my test projects to take advantage of AutoMock:
Usage
Create<T>
You use Mock.Create<T> to create an instance of the service you want to test. AutoMock will use constructor injection to instantiate the service, using its defined Mocks where applicable.
Provide<T>
I created a little shortcut in the TestBase to give AutoMock a reference to use instead of a mock. This will Create the implementation and then add it to AutoMock’s internal list to be used when calling Create in the future.