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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With