-
Manage Mock Dependencies of Controllers with IoC Container - [Test]
2009-09-09
Controllers of a web app usually need the dependent services being injected through constructor via an IoC container. In order to test the controllers, many dependent services need to be mocked, and service calls stubbed.
In most cases, only few of the mocked services are really important for a specific test, and for other controllers, we duplicate similar setup routines in different test classes. These duplicated routines lower the readability of the tests.
While working with Raymand days ago, we tried to manage mock dependencies with Unity container. Here demonstrates the way we used.
ControllerDependencies manages all dependencies used for controllers.
public class ControllerDependencies
{
private readonly IUnityContainer container;
// named mock services are ready for setting up further expectations in test
public readonly IPolicyService PolicyService;
public readonly IQuoteService QuoteService;
// other services
public ControllerDependencies()
{
container = new UnityContainer();
PolicyService = MockRepository.GenerateMock<IPolicyService>();
QuoteService = MockRepository.GenerateMock<IQuoteService>();
// create other mocking instances
container.RegisterInstance<IPolicyService>(PolicyService);
container.RegisterInstance<IQuoteService>(QuoteService);
// register other mocking instances
}
// create a controller instance for test
public T Create<T>() where T : Controller
{
return (T) container.Resolve(typeof(T));
}
public void VerifyAll()
{
PolicyService.VerifyAllExpectations();
QuoteService.VerifyAllExpectations();
// verify against other mock instances
}
}
Below is a test.[Test]
public void SomeActionShouldDoSomething()
{
var dependencies = new ControllerDependencies();
// setup expectation againt named services if needed
dependencies.QuoteService.Expect(r => r.GetQuote("quoteNumber")).Return(new Quote());
var policyController = dependencies.Create<PolicyController>();
var actionResult = policyController.SomeAction();
// asserts go here
dependencies.VerifyAll();
}
ControllerDependencies is reusable for other controllers and could also be the place you put common codes for stubbing the service calls.