//Karthik Srinivasan

Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.

Quirky Personal Projects

LinkedIn

Email me

Moq, Unity and Servicelocator

Feb, 2013

Unit testing code that utilizes Unity, ServiceLocator with Moq framework is a thing of a beauty. Well,not really but a pain if it's your first time. Why? Because if you are a heavy google first, code second type of a developer then googling for Moq + ServiceLocator implementation would only give you Moq + Unity but no ServiceLocator implementation or examples. So, after spending nearly an hr, decided to share or at least remind myself how to for the next time:

Bootstrapping your ServiceLocator:
Note: This is the initialization of Unity in your code
    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            var provider = new UnityServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => provider);

            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            container.RegisterType();

            return container;
        }
    }


Then in your calling method you would do something like this:
     IAssetManager _assetManager = ServiceLocator.Current.GetInstance();


Following is how to moq the above Unity and ServiceLocator instance in Unit test cases:

using Moq;
using Microsoft.Practices.ServiceLocation;

var mockManager = new Mock();
var mockServiceLocator = new Mock();            

mockManager.Setup(assetManager => assetManager.AddToQueue(It.IsAny())).Returns(
 new Models.ResponseMessage()
 {
  Status = "Success"
 });

mockServiceLocator.Setup(x => x.GetInstance()).Returns(mockManager.Object);
ServiceLocator.SetLocatorProvider(new ServiceLocatorProvider(() => mockServiceLocator.Object));

// do your tests..