Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpRequest in ASP.NET 4.0

I've seen a lot of similar threads but none that actually address my particular situation.

I'm writing unit tests in ASP.NET 4.0 web application (ASP.NET Forms, not MVC). There are several spots in the code where I call the ServerVariables collection to call variables like REMOTE_ADDR. Since my unit tests do not actually initiate HttpRequests when executing my code, things like ServerVariables are Null and therefore error when I try to call HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")

All the solutions I've found to address this issue refer to MVC and so they assume that HttpRequest derives from HttpRequestBase, which it does in MVC but not in ASP.NET Forms.

I tried using Moq but you can't mock a sealed class, and HttpRequest is unfortunately sealed with no interface.

like image 1000
Adam Avatar asked Dec 13 '22 20:12

Adam


1 Answers

The HttpRequestBase and HttpRequestWrapper classes can be used with a bit of work.

Wherever you currently access HttpContext.Current.Request -- or just plain Page.Request -- you'll need to use an injectable instance of HttpRequestBase instead. Then you'll need to inject a different subclass of HttpRequestBase depending on whether you're testing or live.

  • For live code, you'd probably inject an HttpRequestWrapper instance that wraps HttpContext.Current.Request:

    var liveRequest = new HttpRequestWrapper(HttpContext.Current.Request);
    
  • For test code, you'd need to create and inject your own mock subclass of HttpRequestBase. Presumably Moq can do that for you on-the-fly.

like image 82
LukeH Avatar answered Dec 29 '22 10:12

LukeH