Testing the lifecycle of components

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));
		}
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s