While writing some sample applications for the upcoming release of Prism (Composite Application Guidance for WPF and Silverlight) I ran into a small challenge.
“How do you verify (with unit tests) that the right classes are registered in your DI-container?”
In my case, the container is Unity, but Unity does not have any ‘IsTypeRegistered’ methods (Apparently there are good reasons for it not to have these methods). So that posses an interesting challenge. At first I thought of 2 solutions:
- Manually create a mock of your container.
Certainly possible but a lot of work for my small demo app. A mocking framework can help with this, but i don’t want to rely on a mocking framework for a small demo app.
- See if the components are registered by resolving the type.
This will work initially, but it will actually instantiate the object. So if the object can’t be created for some reason, your test will fail. Now if the type you have just registered has a lot of dependencies, you will need to satisfy all those dependencies in the container before you can even begin to create the object.
But neither of these options were really satisfying. Then I asked Chris Tavarez, and he mentioned: Why don’t you build a Unity Extension. So I did and that solved the problem quite nicely:
So this is the Extension I’ve created:
And this is how you’d use it:
Hope you find this as useful as I did 🙂