Mocking HttpRequest in ASP.NET 4.0

泪湿孤枕 提交于 2019-12-05 00:53:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3260934/mocking-httprequest-in-asp-net-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!