Unit testing with ServiceLocator
unit-testing, unity-container
Solution
MSDN has this example that shows how to implement the service locator pattern with Unity. Essentially, you should pass the service locator object as a constructor argument of your class. This enables you to pass a `MockUnityResolver`, allowing you to take full control in a unit test.
[TestMethod]
public void InitCallsRunOnNewsController()
{
MockUnityResolver container = new MockUnityResolver();
var controller = new MockNewsController();
container.Bag.Add(typeof(INewsController), controller);
var newsModule = new NewsModule(container);
newsModule.Initialize();
Assert.IsTrue(controller.RunCalled);
}
Problem
I am doing a unit test on a class that uses the unity dependency injection framework. This returns null: ServiceLocator.Current.GetInstance(); How can I get it to return a mock object or just the object itself?