Search code examples
c#browsermoqhttpcontext

Mock User Agent


I'm writing unit tests in which I need a fake HttpContext. I used the HttpSimulator from Phil Haack (http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx). But an function in the Sitecore api throws an exception on the following code:

request.Browser.Browser.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > -1;

I debugged my code and the request.Browser.Browser is empty. I tried to fill the property with Moq but I get an exception. I also tried to add it as a header.

My code looks like this:

using (HttpSimulator simulator = new HttpSimulator("/", "localpath"))
{
    //NameValueCollection nvc = new NameValueCollection { { "User-Agent", "IE" } };
    //simulator.SimulateRequest(new Uri("http://www.foo.bar"), HttpVerb.GET, nvc);
    simulator.SimulateRequest();        

    var browserMock = new Mock<HttpBrowserCapabilities>();
    browserMock.SetupAllProperties();
    //browserMock.SetupProperty(b => b.Browser, "IE");
    HttpContext.Current.Request.Browser = browserMock.Object;
}

Does anyone know how i can mock this property?


Solution

  • This can not be done, you will have to use the HttpContextBase e.d. classes in MVC. Turns out unit testing with web forms is messy(?)