When using an IoC container I like to have confidence that I can retrieve the components that I think I can (rather than getting an unpleasant surprise at runtime!).
This generally involves bootstrapping the container and writing (integration) tests that resolve the types I need. You won’t generally need a test for every class, as retrieving a root object will fail if any of its dependencies cannot be resolved.
While this is a good start, it’s also useful to test the lifecycle of registered components. For example, you want to ensure that your SessionFactory is a singleton. This calls for some helper assertions! (The examples below are tailored for StructureMap, other containers are available :)
using NUnit.Framework;
namespace Your.Namespace.Here
{
public class TestingComponentLifecycles
{
private IContainer container;
[TestFixtureSetUp]
public void FixtureSetUp()
{
container = BootstrapContainer();
}
[Test]
public void SessionFactory()
{
AssertSingleton<SessionFactory>();
}
[Test]
public void Frobulator()
{
AssertTransient<Frobulator>();
}
private void AssertSingleton<T>()
{
var instance1 = container.Resolve<T>();
var instance2 = container.Resolve<T>();
Assert.That(instance1, Is.SameAs(instance2));
}
private void AssertTransient<T>()
{
var instance1 = container.Resolve<T>();
var instance2 = container.Resolve<T>();
Assert.That(instance1, Is.Not.SameAs(instance2));
}
}
}