WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Thursday, April 4, 2013

Moq, Unity and Servicelocator

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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<IAssetManager, AssetManager>();
 
        return container;
    }
}


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


Following is how to moq the above Unity and ServiceLocator instance in Unit test cases:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Moq;
using Microsoft.Practices.ServiceLocation;
 
var mockManager = new Mock<IAssetManager>();
var mockServiceLocator = new Mock<IServiceLocator>();           
 
mockManager.Setup(assetManager => assetManager.AddToQueue(It.IsAny<string>())).Returns(
 new Models.ResponseMessage()
 {
  Status = "Success"
 });
 
mockServiceLocator.Setup(x => x.GetInstance<IAssetManager>()).Returns(mockManager.Object);
ServiceLocator.SetLocatorProvider(new ServiceLocatorProvider(() => mockServiceLocator.Object));
 
// do your tests..

Labels: ,