Wednesday, May 12, 2010

Mocking or Stubbing IUnityContainer

If you ever want to mock the IUnityContainer interface to return particular instances of objects without have to configure the full container, there are some tricks you will need. Unfortunately, you can't just mock or stub the IUnityContainer interface - it seems to work if you have a debugger attached, but if you are just running the test normally, it will fail with a BadImageFormatException. Nice.

It turns out you can mock or stub the UnityContainerBase class, but you can't just mock the Resolve<T> method call as it has not been marked as virtual. However, there is an abstract method in this class that is called into by the Resolve<T> method. Mock or stub it like follows:

var dialog = MockRepository.GenerateStub<IEditDialog<Attachment>>();
dialog.Stub(x => x.DialogResult).Return(result);
var container = MockRepository.GenerateStub<UnityContainerBase>();
container.Stub(x => x.Resolve(typeof(IEditDialog<Attachment>), null)).Return(dialog);

The container object will now return the stub generated in the first line when Resolve<IEditDialog<Attachment>>() is called. Not particularly neat, but neater than configuring the container!

Labels: , ,