Navigation

Search

Categories

On this page

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 35
This Year: 0
This Month: 0
This Week: 0
Comments: 2

Sign In
Pick a theme:

# Thursday, July 14, 2011
Thursday, July 14, 2011 12:47:20 AM (Eastern Daylight Time, UTC-04:00) ( The Geek )

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.

Comments are closed.