Auto mocking with Unity and Moq
As mentioned in my previous post we used the Microsoft Unity container in a previous project. We also used Moq as our mocking library. Combining these two and making an auto mocking container seemed fairly easy, so I went ahead and created something I called UnityAutoMoq.
Now, some say that auto mocking is a bad practice since it can hide certain design flaws in your system, like classes with to many dependencies etc. I say, that if you have these issues, it is probably not the auto mocking that is causing them. Auto mocking can increase your productivity, so I have no issues with using it. In fact, I encourage you to do so.
Using the container
1 // Creating a new instance of the auto mock container 2 var container = new UnityAutoMoqContainer(); 3 4 // Resolving a concrete class automatically creates 5 // mocks for the class dependencies and injects them 6 // before returning an instance of the class 7 Service service = container.Resolve<Service>(); 8 9 // Resolving an interface, returns a mocked 10 // instance of that interface 11 IService mocked = container.Resolve<IService>(); 12 13 // GetMock returns the mock on which you can do setup etc. 14 Mock<IService> mock = container.GetMock<IService>(); 15 16 // Sometimes you need to cast your interface to some other type 17 // This is how that is done 18 container.ConfigureMock<IService>().As<IDisposable>(); 19 Mock<IDisposable> disposable = container.GetMock<IService>().As<IDisposable>();
The framework is available as a NuGet package, and can be installed either using the package manager console in Visual Studio like this:
1 PM> Install-Package UnityAutoMoq
Or by right clicking on references in your project and select the Add Library Package Reference option