All the cool kids do write their own dependency injection container at some point. Today I had to come up with one for testing purposes:
public class MockDependencyResolver : IDependencyResolver
{
private readonly Dictionary<Type, object> collection;
public MockDependencyResolver()
{
collection = new Dictionary<Type, object>();
}
public void Freeze<T>(object mockedObject)
{
collection.Add(typeof(T), mockedObject);
}
public object GetService(Type serviceType)
{
if (collection.ContainsKey(serviceType))
{
return collection[serviceType];
}
var message = String.Format("No object is registered for type {0}", serviceType.Name);
throw new ArgumentException(message);
}
public IEnumerable<object> GetServices(Type serviceType)
{
throw new NotImplementedException();
}
Pretty simple, really. Very simple. And here how I use it in tests:
[TestFixture]
public class SomeClassTests
{
private MockDependencyResolver dependencyResolver;
public void Initialize_GenericInstance_IsValid(String forkName)
{
var dependencyResolver = new MockDependencyResolver();
// this is a part of MVC project, hence MVC internal static reference
System.Web.MVC.DependencyResolver.SetResolver(dependencyResolver);
// I'm using Moq framework
var someService = new Mock<ISomeService>();
dependencyResolver.Freeze<ISomeService>(someService.Object);
someService.Setup(c => c.SomeDepenentOperation()).Verifiable();
// do you tests with someService as a dependency
// inside of the class under test somewhere I have
// DependencyResolver.Current.GetService<ISomeService>(); that would return null
// without mocking of DI
someService.VerifyAll();
}
}