Mocking Request.UserHostAddress in ASP.NET MVC

I spent a lot more time on this tonight than I really should have.

A controller of mine needed to use the value of Request.UserHostAddress and I wanted to mock that value in my unit tests.

I tried, and failed, to get this to work using the MvcContrib.TestHelper assembly. Eventually, I stumbled on a (old) post of Scott Hanselman’s with a class called MvcMockHelpers. I’m using the Moq version of that class.

Simply add the following extension method to that class and you’re good to go:

public static void SetupUserHostAddress(this HttpRequestBase request, string address)
{
    if (address == null) throw new ArgumentNullException("address");

    var mock = Mock.Get(request);

    mock.Setup(x => x.UserHostAddress).Returns(address);
}

And here’s how you use it:

var controller = new ControllerToTest();
controller.SetFakeControllerContext();
controller.Request.SetupUserHostAddress("127.0.0.1");

Voila.