Web Forms – Mocking HttpSession

With thanks to http://stackoverflow.com/users/603670/ben-barreth
at http://stackoverflow.com/questions/1981426/how-do-i-mock-fake-the-session-object-in-asp-net-web-forms

[SetUp]
public void SetUpHttpSessionMock()
{
HttpWorkerRequest _wr = new SimpleWorkerRequest("/dummyWorkerRequest", @"c:\inetpub\wwwroot\dummy", "default.aspx", null, new StringWriter());
HttpContext.Current = new HttpContext(_wr);
HttpSessionStateContainer sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false);
SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionContainer);
}

Refactoring a static class with hard-coded dependencies for testability

is not that hard. You can add a factory method to the static class to create the dependency, and change the factory method at test-time.
Here's an example:

public static class WithDependencies
{
	public static string MethodWithDependencies()
	{
		using (var thing = new HardCodedThing())
		{
			return DoSomething();
		}
	}
}

which can be turned into:

public static class WithDependencies
{
    public static Func<HardCodedThing> CreateHardCodedThing = () => new HardCodedThing();

	public static void MethodWithDependencies()
	{
		using (var thing = CreateHardCodedThing())
		{
			DoSomething();
		}
	}
}

With this code in your test:

[TestFixture]
public class WhenDoingSomething
{
	private Mock<HardCodedThing> mockThing;

	[SetUp]
	public void SetUpMockThing()
	{
		// mockThing.Setup( ...  ) ... etc ...
	}

	public void Given_hardcodedthing_does_X_should_get_Y()
	{
		//Arrange
		WithDependencies.CreateHardCodedThing = () => mockThing.Object;
		//Act
		var result= WithDependencies.MethodWithDependencies();
		//Assert
		Assert.AreEqual("Y", result);
	}
}

Get the Moq Mock from a mock object

Update: See Vladimir's comment below for the built in one-liner.

So there you in your code or possible your debugger and immediate window and you have a mock object and realise you want to change the setup but you didn't keep a reference to the Mock<> ...
So your first though is, no problem, you can cast your object to one of type Castle.Proxies.MyStronglyTypedProxyClass and voila you have access to the Mock property. Except that the compiler doesn't recognise Castle.Proxies.MyStronglyTypedProxyClass as real class.
So then you try reflection to get hold of the Mock property. Which nearly works, but you get a System.Reflection.AmbiguousMatchException : Ambiguous match found. because there's more than one property called Mock (one with and one without a generic parameter).
But this worked for me:

public static Mock<T> GetMockFromObject<T>(T mockedObject) where T : class
{
    PropertyInfo[] pis = mockedObject.GetType().GetProperties()
        .Where(
            p => p.PropertyType.Name == "Mock`1"
        ).ToArray();
    return pis.First().GetGetMethod().Invoke(mockedObject, null) as Mock<T>;
}

hope that helps.