Search code examples
c#.netunit-testinghttprequesthttpcontext

How to mock the UserAgent property for an HttpRequest in a unit test?


I am trying to create a fake HttpContext for my unit test and also wanted to set the UserAgent property.

I tried the below code, but it failed saying platform not supported.

var httpRequest = new HttpRequest(null, "http:xyz.com", null);
httpRequest.Headers["UserAgent"] = "unitTest";

var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
HttpContext context = new HttpContext(httpRequest, httpResponce);

Any help?


Solution

  • As you can see in the reference source, the UserAgent is extracted form the HttpWorkerRequest. The only way to change it, is by calling this constructor of HttpRequest using reflection in order to pass the worker request in:

    internal HttpRequest(HttpWorkerRequest wr, HttpContext context)
    

    As I am further investigating, it seems it retrieves the properties from some far away IIS class, or when using ISAPI using the Server variable ALL_RAW.

    I am starting to think this might become a horrible thing to get mocked up. You might have more luck overriding the abstract class HttpWorkerRequest yourself, but it might become a nightmare to implement.