StructureMapAssert

Following on from a previous post, here’s an updated set of StructureMap assertions:

public static class StructureMapAssert
{
	public static void AssertSingleton<T>(this IContainer container)
	{
		var instance1 = AssertResolvable<T>(container);
		var instance2 = AssertResolvable<T>(container);
		Assert.That(instance1, Is.SameAs(instance2));
	}

	public static void AssertTransient<T>(this IContainer container)
	{
		var instance1 = AssertResolvable<T>(container);
		var instance2 = AssertResolvable<T>(container);
		Assert.That(instance1, Is.Not.SameAs(instance2));
	}

	public static void AssertHttpRequestScoped<T>(this IContainer container)
	{
		T instance2;
		using (new MockHttpContext())
		{
			var instance1 = AssertResolvable<T>(container);
			instance2 = AssertResolvable<T>(container);
			Assert.That(instance1, Is.SameAs(instance2));
		}
		var instance3 = AssertResolvable<T>(container);
		Assert.That(instance3, Is.Not.SameAs(instance2));
	}

	private static T AssertResolvable<T>(this IContainer container)
	{
		try
		{
			return container.GetInstance<T>();
		}
		catch (Exception)
		{
			Console.WriteLine(container.WhatDoIHave());
			throw;
		}
	}

	private class MockHttpContext : IDisposable
	{
		private readonly StringWriter _stringWriter;
		private readonly HttpContext _httpContext;

		public MockHttpContext()
		{
			_httpContext = HttpContext.Current;
			var httpRequest = new HttpRequest("test.aspx", "http://localhost", "?a=1&amp;b=2");
			_stringWriter = new StringWriter();
			var httpResponse = new HttpResponse(_stringWriter);
			HttpContext.Current = new HttpContext(httpRequest, httpResponse);
		}

		public void Dispose()
		{
			_stringWriter.Dispose();
			HttpContext.Current = _httpContext;
		}
	}
}
public class RegistryTests
{
    private IContainer container;
    [TestFixtureSetUp]
    public void FixtureSetUp()
    {
        container = BootstrapContainer();
    }

    [Test]
    public void SessionFactory()
    {
        container.AssertSingleton<ISessionFactory>();
    }

    [Test]
    public void Session()
    {
        container.AssertHttpRequestScoped<ISession>();
    }

    [Test]
    public void ThingyRepository()
    {
        container.AssertTransient<IThingyRepository>();
    }
}

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