为什么模拟HttpContext的,如果它可以被构造? [英] Why mock HttpContext if it can be constructed?

查看:409
本文介绍了为什么模拟HttpContext的,如果它可以被构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直假装/嘲弄/ ASP.NET中的存根的HttpContext某种程度上(在ASP.NET MVC /单轨容易得多)。

I have always been faking/mocking/stubbing HttpContext somehow in ASP.NET (much easier in ASP.NET MVC/MonoRail).

不过,我可以看到自己的HttpContext可轻松构造,字面上夫妇code的行。

But I can see that HttpContext itself can be constructed easily, literally with couple of lines of code.

var tw = new StringWriter();
var workerReq = new SimpleWorkerRequest("/webapp", @"c:\here\there\wwwroot", "page.aspx", tw);
var context = new HtpContext(workerReq);

使用

如果我们把这个包code弄成这个样子,应该很好地工作,也许我们甚至可以渲染ASPX:

If we'll wrap this code into something like this it should work fine, and probably we can even render ASPX using that:

using(Simulate.HttpContext()) {
  HttpContext.Current.BlaBla;
}

所以,问题是:


  1. 为何这样不应该做的。

  2. 为何它应该做的事。

  3. 为什么它没有被广泛使用(其实我不记得任何关于它的帖子)。

我记得菲尔·哈克构建HttpContext的使用反射黑客一个职位。结果
但似乎只是不需要它。

I remember one post where Phill Haack constructed HttpContext using Reflection hacks.
But it seems it is just not needed.

干杯,结果
德米特里。

Cheers,
Dmitriy.

推荐答案

这很好做很简单的测试,但你会如何单元测试,它使用了Htt prequest.Files一个组成部分?据我所知,有没有公共API,让您在SimpleWorkerRequest的指定。即使你能找到在那里你可以设置一个HttpFileCollection属性的位置,请注意,它的构造是内部的,所以你甚至不能创建该类型的实例。

It's fine for doing very simple testing, but how would you unit test a component which uses HttpRequest.Files? As far as I know there are no public APIs to allow you to specify this on SimpleWorkerRequest. Even if you could find a location where you could set an HttpFileCollection property, note that its constructor is internal, so you can't even create an instance of that type.

Htt的prequest.Files不是单独在这方面,实际上有可能是千差万别更多的事情,你的用当前的HttpContext执行不的测试比你的可以的测试。这是真正的抽象派上用场。

HttpRequest.Files is not alone in this regard, and in fact there are probably vastly more things you can't test with the current HttpContext implementation than you can test. This is where abstractions really come in handy.

这篇关于为什么模拟HttpContext的,如果它可以被构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆