Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.
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:
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;
}
}
IAssetManager _assetManager = ServiceLocator.Current.GetInstance();
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..