Created
June 9, 2011 11:28
-
-
Save grahamrhay/1016553 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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&b=2"); | |
_stringWriter = new StringWriter(); | |
var httpResponse = new HttpResponse(_stringWriter); | |
HttpContext.Current = new HttpContext(httpRequest, httpResponse); | |
} | |
public void Dispose() | |
{ | |
_stringWriter.Dispose(); | |
HttpContext.Current = _httpContext; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment