惩戒的Htt prequest在ASP.NET 4.0 [英] Mocking HttpRequest in ASP.NET 4.0
问题描述
我见过很多类似的线程,但没有实际解决我的特殊情况。
I've seen a lot of similar threads but none that actually address my particular situation.
我正在写在ASP.NET 4.0 Web应用程序的单元测试(ASP.NET窗体,而不是MVC)。有在code几个景点,我称之为 ServerVariables
收集调用像 REMOTE_ADDR
变量。由于我的单元测试并没有真正启动的Htt prequests
执行我的code时,像 ServerVariables
是空
,因此错误,当我尝试调用 HttpContext.Current.Request.ServerVariables(REMOTE_ADDR)
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")
我已经找到解决这一问题的参考MVC,所以他们认为的Htt prequest
从的Htt $导出所有解决方案p $ pquestBase
,其中它在MVC,但不是在ASP.NET窗体。
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.
我试着用起订量
,但你不能嘲笑密封类,而的Htt prequest
是遗憾的是,没有接口密封。
I tried using Moq
but you can't mock a sealed class, and HttpRequest
is unfortunately sealed with no interface.
推荐答案
的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.htt$p$pquestbase.aspx\"><$c$c>Htt$p$pquestBase$c$c>和<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.htt$p$pquestwrapper.aspx\"><$c$c>Htt$p$pquestWrapper$c$c>类可以有一些工作可以使用。
The HttpRequestBase
and HttpRequestWrapper
classes can be used with a bit of work.
- 或者只是简单的 Page.Request
- 你会需要使用的Htt prequestBase
的注射实例,而不是。然后你将需要注入的Htt prequestBase
这取决于你正在测试或现场不同的子类。
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.
-
有关现场code,你可能会注入一个包装了
的Htt prequestWrapper
实例HttpContext.Current。请求
:
var liveRequest = new HttpRequestWrapper(HttpContext.Current.Request);
有关测试code,你需要创建和注入的Htt prequestBase
你自己的模拟子类。 presumably起订量可以为你做的即时。
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.
这篇关于惩戒的Htt prequest在ASP.NET 4.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!